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.

[QUESTION] How to manage relationships in (pydantic) models

See original GitHub issue

EDIT: add proper greetings 🙄

Hi guys,

Many thanks for this fantastic repo. It rocks. Not to mention https://dockerswarm.rocks/, I am now in the process to review all my projects from this base 🥇

Here is my question :

How can I declare a one-to-many relationship in the pydantic models?

Context

I have a first object ‘Rule’, that is attached to a second ‘City’.

I have tried the following without success :

rules.py

from app.models.cities import City

class RuleBase(BaseModel):
    mode: Optional[RuleMode] = None
    value: Optional[float] = None
    city: Optional[City] = None

cities.py

class City(BaseModel):
    id: int
    name: str
    rules: Optional[List['Rule']]

Error in tests:

ImportError while loading conftest '/app/app/tests/conftest.py'.
app/app/tests/conftest.py:4: in <module>
    from app.models.cities import City, Rectangle, Point
app/app/models/cities.py:50: in <module>
    class City(BaseModel):
usr/local/lib/python3.6/site-packages/pydantic/main.py:179: in __new__
    config=config,
usr/local/lib/python3.6/site-packages/pydantic/fields.py:118: in infer
    schema=schema,
usr/local/lib/python3.6/site-packages/pydantic/fields.py:87: in __init__
    self.prepare()
usr/local/lib/python3.6/site-packages/pydantic/fields.py:152: in prepare
    self._populate_sub_fields()
usr/local/lib/python3.6/site-packages/pydantic/fields.py:177: in _populate_sub_fields
    self.sub_fields = [self._create_sub_type(t, f'{self.name}_{display_as_type(t)}') for t in types_]
usr/local/lib/python3.6/site-packages/pydantic/fields.py:177: in <listcomp>
    self.sub_fields = [self._create_sub_type(t, f'{self.name}_{display_as_type(t)}') for t in types_]
usr/local/lib/python3.6/site-packages/pydantic/fields.py:210: in _create_sub_type
    model_config=self.model_config,
usr/local/lib/python3.6/site-packages/pydantic/fields.py:87: in __init__
    self.prepare()
usr/local/lib/python3.6/site-packages/pydantic/fields.py:153: in prepare
    self._populate_validators()
usr/local/lib/python3.6/site-packages/pydantic/fields.py:228: in _populate_validators
    else find_validators(self.type_, self.model_config.arbitrary_types_allowed)
usr/local/lib/python3.6/site-packages/pydantic/validators.py:326: in find_validators
    raise RuntimeError(f'error checking inheritance of {type_!r} (type: {display_as_type(type_)})') from e
E   RuntimeError: error checking inheritance of _ForwardRef('Rule') (type: _ForwardRef('Rule'))

Cheers, Emmanuel

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:21 (6 by maintainers)

github_iconTop GitHub Comments

6reactions
fbiducommented, Aug 17, 2020

Hi, I’m sorry for resurrecting an old issue but I just ran into @ebreton’s problem and I’d like to check if this is still the best practice. Considering an example similar to the docs:

item.py:

class Item(ItemBase):
    id: int
    owner: User    # <------ Relationship with User

    class Config:
        orm_mode = True

user.py:

class User(UserBase):
    id: int
    is_active: bool
    items: List[Item] = [] # <------ Relationship with Item

    class Config:
        orm_mode = True

I’d have to import both item from user.py and user from item.py, which would cause a circular import. So I should do something like


ListItem = ForwardRef("List[Item]")
class User(UserBase):
    id: int
    is_active: bool
    items: ListItem = [] # <------ Relationship with Item

    class Config:
        orm_mode = True

User.update_forward_refs()

As my FastAPI application grows, I’d like to break the CRUD into a submodule and the schemas as well. Having back populated relationships like those make things difficult


Update: actually, I couldn’t make it work… Update 2: I think my problem is actually this one samuelcolvin/pydantic#659

4reactions
acidjunkcommented, Nov 26, 2020

What would be the best practice in this situation?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Models with Relationships in FastAPI - SQLModel
Inheritance and Type Annotations¶. The HeroReadWithTeam inherits from HeroRead , which means that it will have the normal fields for reading, including the ......
Read more >
fastapi + sqlalchemy + pydantic → how to process many-to ...
A solution I found. def create_user_groups(db: Session, user_groups: schemas.UserGroupsBase): db_user = db.query(models.User) ...
Read more >
Many-To-Many Relationships In FastAPI - GormAnalysis
In this tutorial, I cover multiple strategies for handling many-to-many relationships using FastAPI with SQLAlchemy and pydantic.
Read more >
tiangolo/fastapi - Gitter
You will be able to declare a Pydantic model with the attributes you care about (or List[Model] , or any type declaration you...
Read more >
How To Use Many-to-Many Database Relationships with ...
Step 1 — Setting Up the Web Application · Step 2 — Setting up Database Models for a Many-to-Many Relationship · Step 3...
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