Two way relation between Pydantic models

Viewed 648

Let's say that a user has multiple posts and a post only has one user. I was wondering if there was a way to specify two-way relations (if it is at all desirable)? When the following is attempted, it results in "NameError: name 'Post' is not defined".

from typing import List
from pydantic import BaseModel

class User(BaseModel):
    id: int
    posts: List[Post]
    
class Post(BaseModel):
    id: int
    user: User

New to Pydantic, any help would be much appreciated!

2 Answers

You can do this by means of postponed annotations:

from typing import List
from pydantic import BaseModel


class User(BaseModel):
    id: int
    posts: "List[Post]"


class Post(BaseModel):
    id: int
    user: User


User.update_forward_refs()

Another approach from the same source:

from __future__ import annotations
from typing import List
from pydantic import BaseModel

class User(BaseModel):
    id: int
    posts: List[Post]
    
class Post(BaseModel):
    id: int
    user: User

user = User(id=1, posts=[])
post = Post(id=1, user=user)

P.S. But it looks like wrong design. It is better to choose one direction.

Related