如何在sqlalchemy中更新多对多的表?

时间:2017-03-26 14:30:51

标签: python flask sqlalchemy

我正在研究烧瓶。尝试写简单的个人博客。问题是如何在帖子中更新标签。 模型是:

tags = db.Table('tags',
  db.Column('tag_id', db.Integer, db.ForeignKey('tag.id')),
  db.Column('post_id', db.Integer, db.ForeignKey('post.id'))
)

class Post(db.Model):
  id = db.Column(db.Integer, primary_key = True)
  title = db.Column(db.String(150), index = True)
  post_preview = db.Column(db.String(500), index = True, unique = True)
  post_body = db.Column(db.Text(), index = True, unique = True)
  date = db.Column(db.DateTime(), index = True)
  tags = db.relationship('Tag', secondary=tags,
      backref=db.backref('posts', lazy='dynamic'))

  def __repr__(self):
    return '<Title %r>' % (self.title)


class Tag(db.Model):
  id = db.Column(db.Integer, primary_key = True)
  text = db.Column(db.String(50), index = True)

  def __repr__(self):
    return self.text

  def __init__(self, txt):
    self.text = txt

我使用此更新表单中的代码更新帖子:

Post.query.filter_by(id = post_id).update({"title":form.title.data, "post_preview":form.post_preview.data, "post_body":form.post_body.data})

这段代码是我需要的,但我认为有办法让它看起来更好。

form_tags=[]
if (form.tags):
    form_tags = form.tags.data.split(',')
for i,t in enumerate(form_tags):
    tmp = t.strip()
    form_tags[i] = tmp

new_tags=[]
old_tags=[]
for t in form_tags:
    obj = Tag.query.filter_by(text=t).first()
    if obj:
        old_tags.append(obj)
    else:
        new_tags.append(t)

for t in old_tags:
    post.tags = old_tags
for t in new_tags:
    post.tags.append(Tag(t))
db.session.commit()

1 个答案:

答案 0 :(得分:0)

试试这个:

post.tags = []
db.session.commit()
for tag in form.tags:
    post.tags.append(tag)