sqlmodel icon indicating copy to clipboard operation
sqlmodel copied to clipboard

Relationship attribute not in model schema

Open carlosporta opened this issue 2 years ago • 4 comments

First Check

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

Commit to Help

  • [X] I commit to help with one of those options 👆

Example Code

from fastapi import FastAPI
from sqlmodel import Field, Relationship, SQLModel, create_engine, Session, select


class Child(SQLModel, table=True):
    __tablename__ = "child"
    id: int = Field(default=None, primary_key=True)
    parent_id: int = Field(default=None, foreign_key="parent.id")
    parent: "Parent" = Relationship(back_populates="children")


class Parent(SQLModel, table=True):
    __tablename__ = "parent"
    id: int = Field(default=None, primary_key=True)
    children: List[Child] = Relationship(
        back_populates="parent",
        sa_relationship_kwargs={"lazy": "joined"},
    )


engine = create_engine("sqlite:///./test.db", connect_args={'check_same_thread': False})
SQLModel.metadata.drop_all(engine)
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
    session.add(Parent(id=0))
    session.add(Child(id=0, parent_id=0))
    session.add(Child(id=1, parent_id=0))
    session.commit()


app = FastAPI()
@app.get("/parent", response_model=Parent)
def get_parent():
    with Session(engine) as session:
        parent = session.exec(select(Parent)).first()
        print(parent)
        # id=0 children=[Child(parent_id=0, id=0), Child(parent_id=0, id=1)]
        return parent


print(Parent.schema())
# {'title': 'Parent', 'type': 'object', 'properties': {'id': {'title': 'Id', 'type': 'integer'}}}
# Repare that there is no children attribute

Description

I have two related models (one parent to many children). And that relationship is eager, as you can see when I select a parent and print it, it is possible to see its children too. But the problem happens when I want to cast the result from the select statement to a parent model, using for example the from_orm function, because there is no attribute named children on the parent schema. My problem is probably related to this issue: #224.

Operating System

Windows

Operating System Details

No response

SQLModel Version

0.0.6

Python Version

3.10.2

Additional Context

No response

carlosporta avatar Feb 28 '22 02:02 carlosporta

I think it's useful,you can see the doc :https://sqlmodel.tiangolo.com/tutorial/fastapi/relationships/

4linuxfun avatar Mar 21 '22 08:03 4linuxfun

Hey @carlosporta! I am facing very similar issue right now. Did you manage to solve this? :)

AdamMisiak avatar Jun 08 '22 17:06 AdamMisiak

@AdamMisiak I had a problem where relationship attributes would not appear at all. Aparently SQLAlchemy 1.4.36 (current version is 1.4.37) breaks relationships (source).

I installed version 1.4.35 and it fixed my issue, hope it fixes yours too!

alp09 avatar Jun 09 '22 18:06 alp09

same issue here

kiddten avatar Jun 20 '22 21:06 kiddten

Hey there @carlosporta! You need to declare a model that explicitly includes the children for the response_model, otherwise you could end up with infinite recursion.

As @4linuxfun says, you can read the docs explaining it, the relevant section is here: https://sqlmodel.tiangolo.com/tutorial/fastapi/relationships/#dont-include-all-the-data


About the issue mentioned by @alp09, that one is reported here: https://github.com/tiangolo/sqlmodel/issues/315, it was solved here: https://github.com/tiangolo/sqlmodel/pull/322, it will be available in the next version, in a couple of hours, SQLModel 0.0.7.

tiangolo avatar Aug 27 '22 18:08 tiangolo