strawberry-sqlalchemy icon indicating copy to clipboard operation
strawberry-sqlalchemy copied to clipboard

Relationship fails when attribute name != column name

Open shish opened this issue 1 year ago • 3 comments

My model has a Survey class with owner_id attribute, which is using a different column name (user_id) for historic reasons

class User(Base):
    __tablename__ = "user"
    user_id: Mapped[int] = mapped_column("id", primary_key=True)
    username: Mapped[str]

class Survey(Base):
    __tablename__ = "survey"
    survey_id: Mapped[int] = mapped_column("id", primary_key=True)
    name: Mapped[str]
    owner_id: Mapped[int] = mapped_column("user_id", ForeignKey("user.id"))
    owner: Mapped[User] = relationship("User", backref="surveys", lazy=True)
import models

@strawberry_sqlalchemy_mapper.type(models.User)
class User:
    pass

@strawberry_sqlalchemy_mapper.type(models.Survey)
class Survey:
    pass

@strawberry.type
class Query:
    @strawberry.field
    def survey(self, info: Info, survey_id: int) -> typing.Optional[Survey]:
        db = info.context["db"]
        return db.execute(select(models.Survey).where(models.Survey.survey_id == survey_id)).scalars().first()

In relationship_resolver_for, the code tries to access getattr(self, sql_column_name) instead of getattr(self, python_attr_name)

query MyQuery {
  survey(surveyId: 1) {
    name
    owner {
      username
    }
  }
}
  File ".../strawberry_sqlalchemy_mapper/mapper.py", line 409, in <listcomp>
    getattr(self, local.key)
AttributeError: 'Survey' object has no attribute 'user_id'

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • We receive the funding once the issue is completed & confirmed by you.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

shish avatar Jul 03 '23 21:07 shish