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!
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With