Lingfeng Xiong
Lingfeng Xiong

Reputation: 1171

How to add object to many-to-one relationship in SQLAlchemy?

I wrote two models like these:

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')

Here we can see, one ItemType can have several ItemTypeComments. Now I wanna add a method to class ItemType to easily add a comment to it. Currently, i wrote:

def add_comment(self, comment):
    comment = ItemTypeComment()
    comment.comment = comment
    comment.itemtype = self
    DBSession.add(comment)

I wanna know if there is any better way doing this? Thanks.

Upvotes: 3

Views: 2054

Answers (1)

jcater
jcater

Reputation: 501

Well, there's nothing wrong with the code you have. You can, however, simplify add_comment a little bit by using the .append() method:

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

This eliminates having to set comment.itemtype, as well as manually adding the new object to your DBSession.

Upvotes: 1

Related Questions