Skip to content

Example: Understanding inheritance and relationships between model classes #488

Open
@clstaudt

Description

@clstaudt

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 Contract(SQLModel):
    """A contract defines the business conditions of a project"""
    title: str = Field(description="Short description of the contract.")
    client: Client = Relationship(
        back_populates="contracts",
    )
    # Contract n:1 Client
    client_id: Optional[int] = Field(
        default=None,
        foreign_key="client.id",
    )

    currency: str  
    term_of_payment: Optional[int] = Field(
        description="How many days after receipt of invoice this invoice is due.",
        default=31,
    )

    
class TimeContract(Contract, table=True):
    """A time-based contract with a rate per time unit"""
    id: Optional[int] = Field(default=None, primary_key=True)

    rate: condecimal(decimal_places=2) = Field(
        description="Rate of remuneration",
    )

    unit: TimeUnit = Field(
        description="Unit of time tracked. The rate applies to this unit.",
        sa_column=sqlalchemy.Column(sqlalchemy.Enum(TimeUnit)),
        default=TimeUnit.hour,
    )

class WorksContract(Contract, table=True):
    """A contract with a fixed price"""
    id: Optional[int] = Field(default=None, primary_key=True)
    price: condecimal(decimal_places=2) = Field(
        description="Price of the contract",
    )
    deliverable: str = Field(description="Description of the deliverable")

class Client(SQLModel, table=True):
    """A client the freelancer has contracted with."""

    id: Optional[int] = Field(default=None, primary_key=True)
    name: str
    contracts: List["Contract"] = Relationship(back_populates="client")

Description

I would like to understand inheritance better using the following example:

  • There are two types of contracts, a time-based contract with a rate per time unit, and a works contract with a fixed price.
  • Every contract is related to a client.

The code example is my first attempt at implementing this. However, It is not yet correct:

InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'mapped class Client->client'. Original exception was: When initializing mapper mapped class Client->client, expression 'Contract' failed to locate a name ('Contract'). If this is a class name, consider adding this relationship() to the <class 'tuttle.model.Client'> class after both dependent classes have been defined.

Questions:

  • Every Contract is related to a client. That makes me think client should be a member of the Contract base class. However, I don't understand how to properly implement the relationship. Is it necessary to move client to the table classes (thereby duplicating it)?
  • When using inheritance from a model class, can I still select from Contract (rather than from the different contract types separately)?

Operating System

macOS, Other

Operating System Details

No response

SQLModel Version

0.0.8

Python Version

3.10

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions