Flask-SQLAlchemy:更新一对多关系

时间:2016-11-02 21:20:02

标签: python flask sqlalchemy flask-sqlalchemy

我有两个型号:

class Project(db.Model):
    __tablename__ = 'project'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64))
    timestamp = db.Column(db.DateTime)
    info = db.Column(db.Text(255))

    post = db.relationship('Post', backref=db.backref('projects'))

class Post(db.Model):
    __tablename__ = 'post'

    id = db.Column(db.Integer, primary_key=True)
    headline = db.Column(db.String(64))
    content = db.Column(db.Text(255))
    timestamp = db.Column(db.DateTime)

    projectId = db.Column(db.Integer, db.ForeignKey('project.id'))

如果我,例如,创建一个帖子实例并通过projectInstance.append(post(headline="...", content="..."))将其附加到项目中  现在我想更新帖子应该属于的项目。除了查询所需的项目之外,还有更简单的方法,将帖子附加到它并从旧项目中删除它吗?

oldProject.remove(post)
newProject.append(post)

1 个答案:

答案 0 :(得分:5)

反过来说:使用Post中的后向引用:

post.projects = newProject

这将处理所需的会话管理。这是一个最小的例子:

In [2]: class A(Base):
   ...:     __tablename__ = 'a'
   ...:     id = Column(Integer, primary_key=True, autoincrement=True)
   ...:     bs = relationship('B', backref='a')
   ...:

In [3]: class B(Base):
   ...:     __tablename__ = 'b'
   ...:     id = Column(Integer, primary_key=True, autoincrement=True)
   ...:     a_id = Column(Integer, ForeignKey('a.id'))
   ...:

In [5]: a1 = A()

In [6]: a2 = A()

In [7]: b = B()

In [8]: a1.bs.append(b)

In [9]: a1.bs
Out[9]: [<__main__.B at 0x7f7322fb52b0>]

In [10]: b.a = a2

In [11]: a1.bs, a2.bs
Out[11]: ([], [<__main__.B at 0x7f7322fb52b0>])

另外,只需将post个实例附加到newProject.post集合处理自动删除,就像我们的as和bs所示:

In [9]: a1.bs.append(b)

In [10]: a1.bs, a2.bs
Out[10]: ([<__main__.B at 0x7f26702565f8>], [])

In [11]: a2.bs.append(b)

In [12]: a1.bs, a2.bs
Out[12]: ([], [<__main__.B at 0x7f26702565f8>])