sqlacodegen
sqlacodegen copied to clipboard
Relationship with foreign_keys as list raising sqlalchemy.exc.ArgumentError exception
The error I'm getting:
sqlalchemy.exc.ArgumentError: Column expression expected for argument 'foreign_keys'; got 'Users.oid'.
The generated code:
class Users(Base):
__tablename__ = "users"
oid = Column(ForeignKey("organisations.id") )
organisations = relationship("Organisations", foreign_keys=["Organisations.created_by"], back_populates="users")
organisations_ = relationship("Organisations", foreign_keys=["Organisations.updated_by"], back_populates="users_")
organisations1 = relationship("Organisations", foreign_keys=[oid], back_populates="users1")
class Organisations(Base):
__tablename__ = "organisations"
created_by = Column(ForeignKey("users.id"))
updated_by = Column(ForeignKey("users.id"))
users = relationship("Users", foreign_keys=[created_by], back_populates="organisations")
users_ = relationship("Users", foreign_keys=[updated_by], back_populates="organisations_")
users1 = relationship("Users", foreign_keys=["Users.oid"], back_populates="organisations1")
The correct code should be:
# the foreign_keys string should include the square brackets
users1 = relationship("Users", foreign_keys="[Users.oid]", back_populates="organisations1")
Ref: https://docs.sqlalchemy.org/en/14/orm/join_conditions.html