Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Call relationship property's "mapper" to materialize lazy direction #2355

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

whiskeyriver
Copy link

A Relationship property from a mapper may not have all expected attributes available immediately. Calling the prop.mapper property will cause these missing attributes to materialize.

I didn't do much investigation, and I'm sure there's probably a better way to do this. I just wanted to submit this in case it was useful at least for diagnosis.

Models

class UserModel(AuditBase):
    __tablename__ = "user"

    emails: Mapped[list[UserEmailModel]] = relationship(
        back_populates="user",
        lazy="selectin",
        order_by=(
            "[UserEmailModel.primary.desc(), UserEmailModel.active.desc(), UserEmailModel.email]"
        ),
    )

class UserEmailModel(AuditBase):
    __tablename__ = "user_email"

    user_id: Mapped[UUID] = mapped_column(ForeignKey("user.id"))
    user: Mapped[UserModel] = relationship(back_populates="emails")

    email: Mapped[str] = mapped_column(unique=True)

IPython Session

In [2]: model = UserEmailModel

In [3]: mapper = model._sa_class_manager.mapper

In [4]: prop = next(mapper.iterate_properties)

In [5]: prop
Out[5]: <Relationship at 0x7f3ba4d72ad0; user>

In [6]: hasattr(prop, "direction")
Out[6]: False

In [7]: prop.mapper
Out[7]: <Mapper at 0x7f3ba4d3b6d0; UserModel>

In [8]: hasattr(prop, "direction")
Out[8]: True

A Relationship property from a mapper may not have all expected
attributes available immediately. Calling the `prop.mapper` property
will cause these missing attributes to materialize.
@whiskeyriver whiskeyriver force-pushed the MaterializeRelationshipDirection branch from 4a536b8 to 18adec9 Compare May 17, 2023 09:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

1 participant