-
-
Notifications
You must be signed in to change notification settings - Fork 760
Closed
Labels
Description
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
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
res234, RaphOb, 4linuxfun, tymetskyi, danielshtel and 6 more