File: fields.py

package info (click to toggle)
python-djantic 0.7.0-6
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 476 kB
  • sloc: python: 2,599; sh: 19; makefile: 14
file content (172 lines) | stat: -rw-r--r-- 4,984 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import logging
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from enum import Enum
from typing import Any, Dict, List, Union
from uuid import UUID

from django.utils.functional import Promise
from pydantic.v1 import IPvAnyAddress, Json
from pydantic.v1.fields import FieldInfo, Required, Undefined

logger = logging.getLogger("djantic")


INT_TYPES = [
    "AutoField",
    "BigAutoField",
    "IntegerField",
    "SmallIntegerField",
    "BigIntegerField",
    "PositiveIntegerField",
    "PositiveSmallIntegerField",
]

STR_TYPES = [
    "CharField",
    "EmailField",
    "URLField",
    "SlugField",
    "TextField",
    "FilePathField",
    "FileField",
]


FIELD_TYPES = {
    "GenericIPAddressField": IPvAnyAddress,
    "BooleanField": bool,
    "BinaryField": bytes,
    "DateField": date,
    "DateTimeField": datetime,
    "DurationField": timedelta,
    "TimeField": time,
    "DecimalField": Decimal,
    "FloatField": float,
    "UUIDField": UUID,
    "JSONField": Union[Json, dict, list],  # TODO: Configure this using default
    "ArrayField": List,
    # "BigIntegerRangeField",
    # "CICharField",
    # "CIEmailField",
    # "CIText",
    # "CITextField",
    # "DateRangeField",
    # "DateTimeRangeField",
    # "DecimalRangeField",
    # "FloatRangeField",
    # "HStoreField",
    # "IntegerRangeField",
    # "RangeBoundary",
    # "RangeField",
    # "RangeOperators",
}


def ModelSchemaField(field: Any, schema_name: str) -> tuple:
    default = Required
    default_factory = None
    description = None
    title = None
    max_length = None
    python_type = None

    if field.is_relation:
        if not field.related_model:
            internal_type = field.model._meta.pk.get_internal_type()
        else:
            internal_type = field.related_model._meta.pk.get_internal_type()
            if not field.concrete and field.auto_created or field.null:
                default = None

        pk_type = FIELD_TYPES.get(internal_type, int)
        if field.one_to_many or field.many_to_many:
            python_type = List[Dict[str, pk_type]]
        else:
            python_type = pk_type

        if field.related_model:
            field = field.target_field

    else:
        if field.choices:
            enum_choices = {}
            for k, v in field.choices:
                if Promise in type(v).__mro__:
                    v = str(v)
                enum_choices[v] = k
            if field.blank:
                enum_choices['_blank'] = ''

            enum_prefix = (
                f"{schema_name.replace('_', '')}{field.name.title().replace('_', '')}"
            )
            python_type = Enum(  # type: ignore
                f"{enum_prefix}Enum",
                enum_choices,
                module=__name__,
            )

            if field.has_default() and isinstance(field.default, Enum):
                default = field.default.value
        else:
            internal_type = field.get_internal_type()
            if internal_type in STR_TYPES:
                python_type = str
                if not field.choices:
                    max_length = field.max_length

            elif internal_type in INT_TYPES:
                python_type = int

            elif internal_type in FIELD_TYPES:
                python_type = FIELD_TYPES[internal_type]

            else:  # pragma: nocover
                for field_class in type(field).__mro__:
                    get_internal_type = getattr(field_class, "get_internal_type", None)
                    if get_internal_type:
                        _internal_type = get_internal_type(field_class())
                        if _internal_type in FIELD_TYPES:
                            python_type = FIELD_TYPES[_internal_type]
                            break

        if python_type is None:
            logger.warning(
                "%s is currently unhandled, defaulting to str.", field.__class__
            )
            python_type = str

        deconstructed = field.deconstruct()
        field_options = deconstructed[3] or {}
        blank = field_options.pop("blank", False)
        null = field_options.pop("null", False)

        if default is Required and field.has_default():
            if callable(field.default):
                default_factory = field.default
                default = Undefined
            else:
                default = field.default
        elif field.primary_key or blank or null:
            default = None

        if default is not None and field.null:
            python_type = Union[python_type, None]

        description = field.help_text
        title = field.verbose_name.title()

    if not description:
        description = field.name

    return (
        python_type,
        FieldInfo(
            default,
            default_factory=default_factory,
            title=title,
            description=str(description),
            max_length=max_length,
        ),
    )