Код: Выделить всё
import uuid
from typing import Union, Optional, TypeAlias
from pydantic import BaseModel, Field, EmailStr
from bson.dbref import DbRef
class User(BaseModel):
id: uuid.UUID = Field(default_factory=uuid.uuid4)
email: EmailStr
class Post(BaseModel):
id: uuid.UUID = Field(default_factory=uuid.uuid4)
title: str
author: Union[User, DBRef]
# --- Simulation of data loading (e.g., using Motor/Beanie) ---
async def load_post_from_db(post_id: uuid.UUID, fetch_author: bool = False) -> Post:
... # if fetch_author is false, author is left as a reference, if not, the referenced object is loaded
При работе с объектом post , пирайт (или mypy) правильно помечает потенциальные ошибки, если мы попытаемся получить доступ к атрибутам, специфичным для пользователя в поле post.author , потому что он может быть Dbrefuuuuure code. />
Код: Выделить всё
async def get_author_email(post_id: uuid.UUID) -> Optional[EmailStr]:
# Assume fetch_author=True was used here for this example
post = await load_post_from_db(post_id, fetch_author=True)
# Type Error from Pyright/MyPy:
# error: Item "email" of "Union[User, DbRef]" has no attribute "email"
# return post.author.email #
Подробнее здесь: [url]https://stackoverflow.com/questions/79592525/static-typing-for-database-schema-models-that-handle-foreign-keys-dbrefs-as-ext[/url]