Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two way relation between Pydantic models

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!

like image 212
Neotenic Primate Avatar asked May 06 '26 22:05

Neotenic Primate


1 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()
like image 112
alex_noname Avatar answered May 08 '26 14:05

alex_noname



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!