Support creating `models.TextChoices` directly from existing `Enum` classes
- Dominant language
- No language data
- Stars
- 188
- Forks
- 7
- PR merge metrics
- No merged PRs in 30d
Description
### Code of Conduct
- [x] I agree to follow Django's Code of Conduct
### Feature Description
This issue proposes adding a helper method to `models.TextChoices` that allows creating a `TextChoices` class directly from an existing Python `Enum` (or `StrEnum`) class.
This would help developers who already define enums elsewhere in their codebase to reuse them easily within Django models, improving code consistency and reducing duplication.
## Example
If this helper method were added to `models.TextChoices`:
```python
class TextChoices(Choices, StrEnum):
"""Class for creating enumerated string choices."""
...
@classmethod
def from_enum(cls, enum_cls, name=None):
"""Create a TextChoices class from an existing Enum class."""
attrs = [(member.name, member.value) for member in enum_cls]
return cls(name or enum_cls.__name__, attrs)
```
Then developers could create `TextChoices` more easily:
```python
from .types import ArticleStatus # an existing Enum class
class Article(models.Model):
status = models.CharField(
choices=models.TextChoices.from_enum(ArticleStatus),
)
```
This approach would make integrating existing enums into Django models more straightforward and DRY.
Thanks in advance for your feedback!
Refs
- https://github.com/rapsealk/django/blob/f93becd062987b457b4aafa7dbf10bdf842888c2/django/db/models/enums.py#L81-L85
- https://forum.djangoproject.com/t/how-can-i-directly-create-a-models-textchoices-from-an-existing-enum-class/43376
### Problem
There is no existing issue or bug — this proposal simply suggests adding a convenience helper method to improve usability.
### Request or proposal
proposal
### Additional Details
_No response_
### Implementation Suggestions
_No response_
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.