sqlacodegen icon indicating copy to clipboard operation
sqlacodegen copied to clipboard

Relationship with foreign_keys as list raising sqlalchemy.exc.ArgumentError exception

Open avacaru opened this issue 3 years ago • 1 comments

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

avacaru avatar Sep 27 '22 11:09 avacaru

this is fixed on 3.0.0b3 and above. Here's the PR that solved it.

ramirotician avatar Dec 01 '22 12:12 ramirotician