Skip to content

Support creating models.TextChoices directly from existing Enum classes #94

@rapsealk

Description

@rapsealk

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

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Status

    Idea

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions