2012-09-10 45 views
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) 

我想知道是否有更好的方法做到這一點?謝謝。

回答

1

那麼,你的代碼沒有問題。你可以,但是,通過使用.append()方法簡化add_comment一點點:

def add_comment(self, comment): 
    comment = ItemTypeComment() 
    self.comments.append(comment) 

這消除了設置comment.itemtype,以及手動添加新的對象添加到您DBSession。

+0

太棒了,謝謝! –

相關問題