-
Notifications
You must be signed in to change notification settings - Fork 2
Open
Description
Code of Conduct
- 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:
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:
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
czueczue
Metadata
Metadata
Assignees
Labels
No labels
Type
Projects
Status
Idea