简体   繁体   中英

Self-referential relations on composite keys using sqlalchemy

I have a model with messages in reply to other messages. Same message_id can be in multiple accounts. I can't find a way to make account and message_id a composite key and use it in relation.

I have gotten this far:

class Message(Base):
    __tablename__ = 'messages'
    id = Column(String(20), primary_key=True)
    account = Column(String(20))
    message_id = Column(String(20))
    in_reply_to_message_id = Column(String(20))
    __table_args__ = (ForeignKeyConstraint([account, in_reply_to_message_id],
                                           ['messages.account', 'messages.message_id']),
                      {})

    parent_message = db.relationship('Message', remote_side=[message_id],
            primaryjoin=('Message.account==Message.account and Message.in_reply_to_message_id==Message.message_id'),
            backref=backref('child_messages'), uselist=False)

When I try to do message.parent_message , the query generated is missing account comparison in where clause -

WHERE %(param_1)s = messages.message_id

Also I get the warning:

SAWarning: Multiple rows returned with uselist=False for lazily-loaded attribute 'Tweet.parent_tweet' 
  % self.parent_property)

How can the relationship be setup to properly take care of the account as part of composite key in this case.

Finally it was as simple as doing the following -

parent_message = db.relationship("Message",
                    backref="child_messages",
                    remote_side=[account, message_id]
              )

The key was in using the remote_side with composite key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM