2
我寫了兩個模型,如這些:如何將對象添加到SQLAlchemy中的多對一關係中?
class ItemType(Base, DBBase):
__tablename__ = 'itemtypes'
id = Column(Integer, primary_key = True)
name = Column(String), nullable = True)
comments = relationship('ItemTypeComment')
class ItemTypeComment(Base, DBBase):
__tablename__ = 'itemtypecomments'
id = Column(Integer, primary_key = True)
comment = Column(String), nullable = True)
itemtype_id = Column(Integer, ForeignKey('itemtypes.id'), nullable = True)
itemtype = relationship('ItemType')
在這裏我們可以看到,一個ItemType的能有幾個ItemTypeComments。現在我想要添加一個方法到類ItemType來輕鬆添加評論。目前,我寫道:
def add_comment(self, comment):
comment = ItemTypeComment()
comment.comment = comment
comment.itemtype = self
DBSession.add(comment)
我想知道是否有更好的方法做到這一點?謝謝。
太棒了,謝謝! –