Debian Codegraph @

beanie/odm/utils/projection.py

raw
1 from typing import TypeVar
2
3 from pydantic import BaseModel
4
5 from beanie.odm.interfaces.detector import ModelType
6 from beanie.odm.utils.pydantic import get_config_value, get_model_fields
7
8 ProjectionModelType = TypeVar("ProjectionModelType", bound=BaseModel)
9
10
11 def get_projection(
12 model: type[ProjectionModelType],
13 ) -> dict[str, int] | None:
14 if hasattr(model, "get_model_type") and (
15 model.get_model_type() is ModelType.UnionDoc # type: ignore
16 or ( # type: ignore
17 model.get_model_type() is ModelType.Document # type: ignore
18 and model._inheritance_inited # type: ignore
19 )
20 ): # type: ignore
21 return None
22
23 if hasattr(model, "Settings"): # MyPy checks
24 settings = model.Settings
25
26 if hasattr(settings, "projection"):
27 return settings.projection
28
29 if get_config_value(model, "extra") == "allow":
30 return None
31
32 document_projection: dict[str, int] = {}
33
34 for name, field in get_model_fields(model).items():
35 document_projection[field.alias or name] = 1
36 return document_projection