Skip to content

How to access a parent model's relationship's attributes #77

@yudjinn

Description

@yudjinn

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the SQLModel documentation, with the integrated search.
  • I already searched in Google "How to X in SQLModel" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to SQLModel but to Pydantic.
  • I already checked if it is not related to SQLModel but to SQLAlchemy.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

class UserBase(Base):
    username: str
    in_game_name: str
    discord_name: Optional[str] = Field(default=None)
    is_active: Optional[bool] = Field(default=True)
    is_superuser: Optional[bool] = Field(default=False)

    company: Optional[CompanyUser] = Relationship(back_populates="company")


class UserRead(UserBase):
    rank: str = UserBase.company.rank

---------
class CompanyUser(SQLModel, table=True):
    """
    Link Table to store ranks between users and a company
    """

    company_id: uuid.UUID = Field(foreign_key="company.id", primary_key=True)
    user_id: uuid.UUID = Field(foreign_key="user.id", primary_key=True)

    rank: str

    company: "CompanyBase" = Relationship(back_populates="members")
    user: "UserBase" = Relationship(back_populates="company")


class CompanyBase(Base):
    name: str
    logo_id: Optional[uuid.UUID] = Field(default=None, foreign_key="file.id")

    members: List[CompanyUser] = Relationship(back_populates="user")

Description

Erroring on UserRead>rank: UserBase has no attribute "company".

Effectively, I'm unsure how to access the parent model's relationships.

Operating System

Linux, Windows

Operating System Details

No response

SQLModel Version

0.0.4

Python Version

3.9.7

Additional Context

Trying to follow this guide on link tables with attributes: https://sqlmodel.tiangolo.com/tutorial/many-to-many/link-with-extra-fields/

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions