question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Relationship attribute not in model schema

See original GitHub issue

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

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:11
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

14reactions
alp09commented, Jun 9, 2022

@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!

0reactions
tiangolocommented, Aug 27, 2022

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.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Attributes to Relationships in ER Model - GeeksforGeeks
In ER model, entities have attributes which can be of various types like single-valued, multi-valued, composite, simple, stored, derived and ...
Read more >
Chapter 8 The Entity Relationship Data Model
ER models, also called an ER schema, are represented by ER diagrams. ... However, the information about attribute domain is not presented on...
Read more >
Schema with relationship is not saved in db - node.js
in this case the const zooInfo have the data of req.body.geographicalArea.name but when it gets to the line const zooSave = await zoo....
Read more >
How to deal with relationship attributes? - Medium
In this article, we will be deconstructing the steps our mind goes through when “translating” from the relational model to the GraphQL schema....
Read more >
Models with Relationships in FastAPI - SQLModel
Now, notice that these new fields team and heroes are not declared with Relationship() , because these are not table models, they cannot...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found