https://github.com/bellini666/django-choices-field
Django field that set/get django's new TextChoices/IntegerChoices enum
https://github.com/bellini666/django-choices-field
django enum
Last synced: 4 months ago
JSON representation
Django field that set/get django's new TextChoices/IntegerChoices enum
- Host: GitHub
- URL: https://github.com/bellini666/django-choices-field
- Owner: bellini666
- License: mit
- Created: 2021-07-17T13:01:50.000Z (almost 4 years ago)
- Default Branch: master
- Last Pushed: 2025-01-14T22:31:59.000Z (6 months ago)
- Last Synced: 2025-03-19T05:55:49.235Z (4 months ago)
- Topics: django, enum
- Language: Python
- Homepage:
- Size: 188 KB
- Stars: 9
- Watchers: 1
- Forks: 5
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# django-choices-field
[](https://actions-badge.atrox.dev/bellini666/django-choices-field/goto?ref=master)
[](https://codecov.io/gh/bellini666/django-choices-field)
[](https://pypi.org/project/django-choices-field/)

Django field that set/get django's new TextChoices/IntegerChoices enum.
## Install
```bash
pip install django-choices-field
```## Usage
```python
import enumfrom django.db import models
from django_choices_field import TextChoicesField, IntegerChoicesField, IntegerChoicesFlagclass MyModel(models.Model):
class TextEnum(models.TextChoices):
FOO = "foo", "Foo Description"
BAR = "bar", "Bar Description"class IntegerEnum(models.IntegerChoices):
FIRST = 1, "First Description"
SECOND = 2, "Second Description"class IntegerFlagEnum(IntegerChoicesFlag):
FIRST = enum.auto(), "First Option"
SECOND = enum.auto(), "Second Option"
THIRD = enum.auto(), "Third Option"text_field = TextChoicesField(
choices_enum=TextEnum,
default=TextEnum.FOO,
)
integer_field = IntegerChoicesField(
choices_enum=IntegerEnum,
default=IntegerEnum.FIRST,
)
flag_field = IntegerChoicesFlagField(
choices_enum=IntegerFlagEnum,
default=IntegerFlagEnum.FIRST | IntegerFlagEnum.SECOND,
)obj = MyModel()
reveal_type(obj.text_field) # MyModel.TextEnum.FOO
assert isinstance(obj.text_field, MyModel.TextEnum)
assert obj.text_field == "foo"reveal_type(obj.integer_field) # MyModel.IntegerEnum.FIRST
assert isinstance(obj.integer_field, MyModel.IntegerEnum)
assert obj.integer_field == 1reveal_type(obj.flag_field) # MyModel.IntegerFlagEnum.FIRST | MyModel.IntegerFlagEnum.SECOND
assert isinstance(obj.integer_field, MyModel.IntegerFlagEnum)
assert obj.flag_field == 3
```NOTE: The `IntegerChoicesFlag` requires python 3.11+ to work properly.
## License
This project is licensed under MIT licence (see `LICENSE` for more info)
## Contributing
Make sure to have [poetry](https://python-poetry.org/) installed.
Install dependencies with:
```bash
poetry install
```Run the testsuite with:
```bash
poetry run pytest
```Feel free to fork the project and send me pull requests with new features,
corrections and translations. I'll gladly merge them and release new versions
ASAP.