File: fields.py

package info (click to toggle)
django-choices-field 3.1.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 200 kB
  • sloc: python: 600; sh: 18; makefile: 3
file content (229 lines) | stat: -rw-r--r-- 7,980 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import functools
import itertools
from typing import (
    Callable,
    ClassVar,
    Dict,
    List,
    Optional,
    Sequence,
    Tuple,
    Type,
    Union,
    cast,
)

from django.core.exceptions import ValidationError
from django.db import models

from .types import IntegerChoicesFlag


def _get_flag_description(descs: Sequence[str]) -> str:
    return "|".join(str(desc) for desc in descs)


def _get_integer_enum_members(choices: List[Tuple[Union[int, None], str]]) -> Dict[str, int]:
    # choices can contain the `None` key which can't be mapped to an enum. See
    # Django Model Field docs about Enumeration Types for more info about
    # labelling empty states with `__empty__`.
    filtered_choices = [(k, v) for (k, v) in choices if k is not None]
    return {desc.replace(" ", "_").upper(): value for value, desc in filtered_choices}


try:
    from django.utils.functional import Promise, lazy
except ImportError:  # pragma: nocover
    Promise = None
    _get_flag_description_lazy = None
else:
    _get_flag_description_lazy = cast(
        Callable[[Sequence[str]], str],
        lazy(_get_flag_description, str),
    )


class TextChoicesField(models.CharField):
    description: ClassVar[str] = "TextChoices"
    default_error_messages: ClassVar[Dict[str, str]] = {
        "invalid": "“%(value)s” must be a subclass of %(enum)s.",
    }

    def __init__(
        self,
        choices_enum: Optional[Type[models.TextChoices]] = None,
        verbose_name: Optional[str] = None,
        name: Optional[str] = None,
        **kwargs,
    ):
        if choices_enum is not None:
            self.choices_enum = choices_enum
            if getattr(self, "null", False) or kwargs.get("null"):
                kwargs["choices"] = choices_enum.choices
            else:
                kwargs["choices"] = [
                    (k, v) for (k, v) in choices_enum.choices if cast(object, k) is not None
                ]
        elif "choices" in kwargs:
            self.choices_enum = models.TextChoices(
                "ChoicesEnum",
                [(k, (k, v)) for k, v in kwargs["choices"] if k is not None],
            )
        else:
            raise TypeError("either of choices_enum or choices must be provided")
        kwargs.setdefault(
            "max_length",
            max(len(c[0]) for c in kwargs["choices"] if c[0] is not None),
        )
        super().__init__(verbose_name=verbose_name, name=name, **kwargs)

    def to_python(self, value):
        if value in self.empty_values:
            return None

        try:
            return self.choices_enum(value)
        except ValueError as e:
            raise ValidationError(
                self.error_messages["invalid"],
                code="invalid",
                params={"value": value, "enum": self.choices_enum},
            ) from e

    def from_db_value(self, value, expression, connection):
        return self.to_python(value)

    def get_prep_value(self, value):
        value = super().get_prep_value(value)
        return self.to_python(value)


class IntegerChoicesField(models.IntegerField):
    description: ClassVar[str] = "IntegerChoices"
    default_error_messages: ClassVar[Dict[str, str]] = {
        "invalid": "“%(value)s” must be a subclass of %(enum)s.",
    }

    def __init__(
        self,
        choices_enum: Optional[Type[models.IntegerChoices]] = None,
        verbose_name: Optional[str] = None,
        name: Optional[str] = None,
        **kwargs,
    ):
        if choices_enum is not None:
            self.choices_enum = choices_enum
            if getattr(self, "null", False) or kwargs.get("null"):
                kwargs["choices"] = choices_enum.choices
            else:
                kwargs["choices"] = [
                    (k, v) for (k, v) in choices_enum.choices if cast(object, k) is not None
                ]
        elif "choices" in kwargs:
            enum_members = _get_integer_enum_members(kwargs["choices"])
            self.choices_enum = models.IntegerChoices("ChoicesEnum", enum_members)
        else:
            raise TypeError("either of choices_enum or choices must be provided")
        super().__init__(verbose_name=verbose_name, name=name, **kwargs)

    def to_python(self, value):
        if value is None:
            return None

        try:
            return self.choices_enum(int(value) if isinstance(value, str) else value)
        except ValueError as e:
            raise ValidationError(
                self.error_messages["invalid"],
                code="invalid",
                params={"value": value, "enum": self.choices_enum},
            ) from e

    def from_db_value(self, value, expression, connection):
        return self.to_python(value)

    def get_prep_value(self, value):
        value = super().get_prep_value(value)
        return self.to_python(value)

    def formfield(self, **kwargs):  # pragma:nocover
        return super().formfield(
            **{
                "coerce": self.to_python,
                **kwargs,
            },
        )


class IntegerChoicesFlagField(models.IntegerField):
    description: ClassVar[str] = "IntegerChoicesFlag"
    default_error_messages: ClassVar[Dict[str, str]] = {
        "invalid": "“%(value)s” must be a subclass of %(enum)s.",
    }

    def __init__(
        self,
        choices_enum: Optional[Type[IntegerChoicesFlag]] = None,
        verbose_name: Optional[str] = None,
        name: Optional[str] = None,
        **kwargs,
    ):
        if choices_enum is not None:
            self.choices_enum = choices_enum

            if getattr(self, "null", False) or kwargs.get("null"):
                kwargs["choices"] = choices_enum.choices
            else:
                kwargs["choices"] = [
                    (k, v) for (k, v) in choices_enum.choices if cast(object, k) is not None
                ]
            default_choices = [(x.value, x.label) for x in choices_enum]
            for i in range(1, len(default_choices)):
                for combination in itertools.combinations(default_choices, i + 1):
                    value = functools.reduce(lambda a, b: a | b[0], combination, 0)

                    descs = [c[1] for c in combination]
                    if Promise is not None and any(isinstance(desc, Promise) for desc in descs):
                        assert _get_flag_description_lazy is not None
                        desc = _get_flag_description_lazy(descs)
                    else:
                        desc = _get_flag_description(descs)

                    kwargs["choices"].append((value, desc))
        elif "choices" in kwargs:
            default_choices_length = len(kwargs["choices"]).bit_length()
            default_choices = [kwargs["choices"][i] for i in range(default_choices_length)]
            enum_members = _get_integer_enum_members(default_choices)
            self.choices_enum = models.IntegerChoices("ChoicesEnum", enum_members)
        else:
            raise TypeError("either of choices_enum or choices must be provided")

        super().__init__(verbose_name=verbose_name, name=name, **kwargs)

    def to_python(self, value):
        if value is None:
            return None

        try:
            return self.choices_enum(int(value) if isinstance(value, str) else value)
        except ValueError as e:
            raise ValidationError(
                self.error_messages["invalid"],
                code="invalid",
                params={"value": value, "enum": self.choices_enum},
            ) from e

    def from_db_value(self, value, expression, connection):
        return self.to_python(value)

    def get_prep_value(self, value):
        value = super().get_prep_value(value)
        return self.to_python(value)

    def formfield(self, **kwargs):  # pragma:nocover
        return super().formfield(
            **{
                "coerce": self.to_python,
                **kwargs,
            },
        )