Debian Codegraph @

ninja/orm/fields.py

raw symbols SCIP
1 import datetime
2 from decimal import Decimal
3 from typing import Any, Callable, Dict, List, Tuple, Type, TypeVar, Union, no_type_check
4 from uuid import UUID
5
6 from django.db.models import ManyToManyField
7 from django.db.models.fields import Field as DjangoField
8 from pydantic import IPvAnyAddress
9 from pydantic.fields import FieldInfo
10 from pydantic_core import PydanticUndefined, core_schema
11
12 from ninja.errors import ConfigError
13 from ninja.openapi.schema import OpenAPISchema
14 from ninja.types import DictStrAny
15
16 __all__ = ["create_m2m_link_type", "get_schema_field", "get_related_field_schema"]
17
18
19 # keep_lazy seems not needed as .title forces translation anyway
20 # https://github.com/vitalik/django-ninja/issues/774
21 # @keep_lazy_text
22 def title_if_lower(s: str) -> str:
23 if s == s.lower():
24 return s.title()
25 return s
26
27
28 class AnyObject:
29 @classmethod
30 def __get_pydantic_core_schema__(
31 cls, source: Any, handler: Callable[..., Any]
32 ) -> Any:
33 return core_schema.with_info_plain_validator_function(cls.validate)
34
35 @classmethod
36 def __get_pydantic_json_schema__(
37 cls, schema: Any, handler: Callable[..., Any]
38 ) -> DictStrAny:
39 return {"type": "object"}
40
41 @classmethod
42 def validate(cls, value: Any, _: Any) -> Any:
43 return value
44
45
46 TYPES = {
47 "AutoField": int,
48 "BigAutoField": int,
49 "BigIntegerField": int,
50 "BinaryField": bytes,
51 "BooleanField": bool,
52 "CharField": str,
53 "DateField": datetime.date,
54 "DateTimeField": datetime.datetime,
55 "DecimalField": Decimal,
56 "DurationField": datetime.timedelta,
57 "FileField": str,
58 "FilePathField": str,
59 "FloatField": float,
60 "GenericIPAddressField": IPvAnyAddress,
61 "IPAddressField": IPvAnyAddress,
62 "IntegerField": int,
63 "JSONField": AnyObject,
64 "NullBooleanField": bool,
65 "PositiveBigIntegerField": int,
66 "PositiveIntegerField": int,
67 "PositiveSmallIntegerField": int,
68 "SlugField": str,
69 "SmallAutoField": int,
70 "SmallIntegerField": int,
71 "TextField": str,
72 "TimeField": datetime.time,
73 "UUIDField": UUID,
74 # postgres fields:
75 "ArrayField": List,
76 "CICharField": str,
77 "CIEmailField": str,
78 "CITextField": str,
79 "HStoreField": Dict,
80 }
81
82 TModel = TypeVar("TModel")
83
84
85 def register_field(django_field: str, python_type: Any) -> None:
86 TYPES[django_field] = python_type
87
88
89 @no_type_check
90 def create_m2m_link_type(type_: Type[TModel]) -> Type[TModel]:
91 class M2MLink(type_): # type: ignore
92 @classmethod
93 def __get_pydantic_core_schema__(cls, source, handler):
94 return core_schema.with_info_plain_validator_function(cls._validate)
95
96 @classmethod
97 def __get_pydantic_json_schema__(cls, schema, handler):
98 json_type = {
99 int: "integer",
100 str: "string",
101 float: "number",
102 UUID: "string",
103 }[type_]
104 return {"type": json_type}
105
106 @classmethod
107 def _validate(cls, v: Any, _):
108 try:
109 return v.pk # when we output queryset - we have db instances
110 except AttributeError:
111 return type_(v) # when we read payloads we have primakey keys
112
113 return M2MLink
114
115
116 @no_type_check
117 def get_schema_field(
118 field: DjangoField, *, depth: int = 0, optional: bool = False
119 ) -> Tuple:
120 "Returns pydantic field from django's model field"
121 alias = None
122 default = ...
123 default_factory = None
124 description = None
125 title = None
126 max_length = None
127 nullable = False
128 python_type = None
129
130 if field.is_relation:
131 if depth > 0:
132 return get_related_field_schema(field, depth=depth)
133
134 internal_type = field.related_model._meta.pk.get_internal_type()
135
136 if not field.concrete and field.auto_created or field.null or optional:
137 default = None
138 nullable = True
139
140 alias = getattr(field, "get_attname", None) and field.get_attname()
141
142 pk_type = TYPES.get(internal_type, int)
143 if field.one_to_many or field.many_to_many:
144 m2m_type = create_m2m_link_type(pk_type)
145 python_type = List[m2m_type] # type: ignore
146 else:
147 python_type = pk_type
148
149 else:
150 _f_name, _f_path, _f_pos, field_options = field.deconstruct()
151 blank = field_options.get("blank", False)
152 null = field_options.get("null", False)
153 max_length = field_options.get("max_length")
154
155 internal_type = field.get_internal_type()
156 try:
157 python_type = TYPES[internal_type]
158 except KeyError as e:
159 msg = [
160 f"Do not know how to convert django field '{internal_type}'.",
161 "Try from ninja.orm import register_field",
162 f"register_field('{internal_type}', <your-python-type>)",
163 ]
164 raise ConfigError("\n".join(msg)) from e
165
166 if field.primary_key or blank or null or optional:
167 default = None
168 nullable = True
169
170 if field.has_default():
171 if callable(field.default):
172 default_factory = field.default
173 else:
174 default = field.default
175
176 if default_factory:
177 default = PydanticUndefined
178
179 if nullable:
180 python_type = Union[python_type, None] # aka Optional in 3.7+
181
182 description = field.help_text or None
183 title = title_if_lower(field.verbose_name)
184
185 return (
186 python_type,
187 FieldInfo(
188 default=default,
189 alias=alias,
190 validation_alias=alias,
191 serialization_alias=alias,
192 default_factory=default_factory,
193 title=title,
194 description=description,
195 max_length=max_length,
196 ),
197 )
198
199
200 @no_type_check
201 def get_related_field_schema(field: DjangoField, *, depth: int) -> Tuple[OpenAPISchema]:
202 from ninja.orm import create_schema
203
204 model = field.related_model
205 schema = create_schema(model, depth=depth - 1)
206 default = ...
207 if not field.concrete and field.auto_created or field.null:
208 default = None
209 if isinstance(field, ManyToManyField):
210 schema = List[schema] # type: ignore
211
212 return (
213 schema,
214 FieldInfo(
215 default=default,
216 description=field.help_text,
217 title=title_if_lower(field.verbose_name),
218 ),
219 )