jethar
jethar

Reputation: 2373

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.

Upvotes: 1

Views: 617

Answers (1)

jethar
jethar

Reputation: 2373

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.

Upvotes: 1

Related Questions