| 874 | |
| 875 | |
| 876 | class IntEnumFieldInstance(SmallIntField): |
| 877 | def __init__( |
| 878 | self, |
| 879 | enum_type: type[IntEnum], |
| 880 | description: str | None = None, |
| 881 | generated: bool = False, |
| 882 | **kwargs: Any, |
| 883 | ) -> None: |
| 884 | # Validate values |
| 885 | minimum = 1 if generated else -32768 |
| 886 | for item in enum_type: |
| 887 | try: |
| 888 | value = int(item.value) |
| 889 | except ValueError: |
| 890 | raise ConfigurationError("IntEnumField only supports integer enums!") |
| 891 | if not minimum <= value < 32768: |
| 892 | raise ConfigurationError( |
| 893 | f"The valid range of IntEnumField's values is {minimum}..32767!" |
| 894 | ) |
| 895 | |
| 896 | # Automatic description for the field if not specified by the user |
| 897 | if description is None: |
| 898 | description = "\n".join([f"{e.name}: {int(e.value)}" for e in enum_type])[:2048] |
| 899 | |
| 900 | super().__init__(description=description, **kwargs) |
| 901 | self.enum_type = enum_type |
| 902 | |
| 903 | def to_python_value(self, value: int | None) -> IntEnum | None: |
| 904 | value = self.enum_type(value) if value is not None else None |
| 905 | return value |
| 906 | |
| 907 | def to_db_value(self, value: IntEnum | None | int, instance: type[Model] | Model) -> int | None: |
| 908 | if isinstance(value, IntEnum): |
| 909 | value = int(value.value) |
| 910 | if isinstance(value, int): |
| 911 | value = int(self.enum_type(value)) |
| 912 | self.validate(value) |
| 913 | return value |
| 914 | |
| 915 | |
| 916 | IntEnumType = TypeVar("IntEnumType", bound=IntEnum) |
no outgoing calls
no test coverage detected
searching dependent graphs…