Skip to content

Bug: SQLAlchemy factory doesn't work properly with association_proxy #787

@AlexPetul

Description

@AlexPetul

Description

I tried to add a simple proxy to existing User and UserKeywordAssociation models, but the test case test_association_proxy fails (see the logs section).

PS: found this issue accidentally, while adding support to sqlalchemy dataclass mapping

URL to code causing the issue

No response

MCVE

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True)
    name = Column(String)

    user_keyword_associations = relationship(
        "UserKeywordAssociation",
        back_populates="user",
        lazy="selectin",
    )
    keywords = association_proxy(
        "user_keyword_associations", "keyword", creator=lambda keyword_obj: UserKeywordAssociation(keyword=keyword_obj)
    )

    # I added this simple proxy here.
    keyword_names = association_proxy(
        "user_keyword_associations",
        "name",
    )


class UserKeywordAssociation(Base):
    __tablename__ = "user_keyword"

    user_id = Column(Integer, ForeignKey("users.id"), primary_key=True)
    keyword_id = Column(Integer, ForeignKey("keywords.id"), primary_key=True)

    user = relationship(User, back_populates="user_keyword_associations")
    keyword = relationship("Keyword", lazy="selectin")
    
    # I added this field here.
    name = Column(String)

    # for prevent mypy error: Unexpected keyword argument "keyword" for "UserKeywordAssociation"  [call-arg]
    def __init__(self, keyword: Optional["Keyword"] = None):
        self.keyword = keyword

Steps to reproduce

Screenshots

No response

Logs

polyfactory/factories/sqlalchemy_factory.py:304: in get_model_fields
    class_ = target_attr.entity.class_


FAILED tests/sqlalchemy_factory/test_association_proxy.py::test_association_proxy - AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with UserKeywordAssociation.name has an attribute 'entity'. Did you mean: 'identity'?

Release Version

latest

Platform

  • Linux
  • Mac
  • Windows
  • Other (Please specify in the description above)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions