Hello, everyone
I have a User model and a Conversation model
class Conversation(Base):
__tablename__ = 'conversations'
id = Column(Integer, primary_key=True)
user1 = Column(Integer, Foreignusers.id'), unique=False, nullable=False)
user2 = Column(Integer, ForeignKey('users.id'), unique=False, nullable=False)
date = Column(DateTime, unique=False, nullable=False, default=dt.utcnow)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
userName = Column(String, unique=False, nullable=True)
Im trying to add a relationship() to User model which should return all conversations where Conversation.user1 or Conversation.user2 is the selected User
I tried:
conversations = relationship('Conversation', backref="Users")
Which results to this error when I was trying to get the User:
AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship User.conversations - there are multiple foreign key paths linking the tables. Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference to the parent table.
I realized I have to specify columns..
So I tried:
conversations = relationship(Conversation, foreign_keys=[Conversation.user1, Conversation.user2], backref="Users")
and
and again same error!conversations = relationship(Conversation, foreign_keys='[Conversation.user1, Conversation.user2]', backref="Users")
After that I tried:
conversations = relationship(Conversation, foreign_keys=Conversation.user1 or Conversation.user2, backref="Users")
Which returned this error on commiting my Conversation object:
RecursionError: maximum recursion depth exceeded
Again I tried to use this:
conversations = relationship(Conversation, foreign_keys=['Conversation.user1', 'Conversation.user2'], backref="Users")
And it gave me this error on getting the User object:
ArgumentError: Column-based expression object expected for argument 'foreign_keys'; got: 'Conversation.user1', type class 'str'
Also I tried to get only one specific column by defining it using foreign_keys but it gave me the same RecursionError
I know I can do it by adding a method to User class like:
def conversations(self): return session.query(Conversation).filter(Conversation.user1 == self.id or Conversation.user2 == self.id).all()But it's important for me to do it using relationship()..
conversations = sqlalchemy.orm.relationship("Conversation",
primaryjoin="""or_(User.id==Conversation.user_id_1,
User.id==Conversation.user_id_2,
)""",
order_by="Conversation.id.desc()",
)primaryjoin="or_(User.id == Conversation.user1, User.id == Conversation.user2)"