2012-09-10 42 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

太棒了,谢谢! –

相关问题