Named Groups for Enumeration Types

154 views
Skip to first unread message

Steven Johnson

unread,
Aug 3, 2022, 9:25:50 AM8/3/22
to Django developers (Contributions to Django itself)
Hello all,

In my project I recently wanted to group choices, and have gotten used to the Enumeration Types Django provides. I noticed Django currently does not support named groups for these.

So, I've implemented them in two ways:
Option A) Ugly, but simple changes to Django

class Media(models.TextChoices):
    _named_group1 = "Audio"
    VINYL = "vinyl"
    CD = "cd", "CD"
    _named_group2 = "Video"
    VHS_TAPE = "vhs", "VHS Tape"
    DVD = "dvd", _("DVD")
    _named_group3 = None
    UNKNOWN = "unknown"

Option B) Pretty, but complex changes to Django

class Media(models.TextChoices):
    class Audio(models.TextChoices):
        VINYL = "vinyl"
        CD = "cd", "CD"

    class Video(models.TextChoices):
        VHS_TAPE = "vhs", "VHS Tape"
        DVD = "dvd", _("DVD")

    UNKNOWN = "unknown"

Does anyone have better ideas to implement named groups here? Would one of these implementations be useful for Django?
Below are links to personal pull requests to see potential patches. The pull requests include tests and documentation.

GitHub links:
Relevant docs:

Thank you,
Steven H Johnson

Adam Johnson

unread,
Aug 24, 2022, 8:02:34 AM8/24/22
to Django developers (Contributions to Django itself)
Hi Steven

I agree that grouped choices would be nice to support in the enum types. Thank you for taking a look at this.

I'm not sure about either of your proposed syntaxes. They both seem error prone and unclear to me. I propose instead using a separate grouping attribute:

class Media(models.TextChoices):

    VINYL = "vinyl"
    CD = "cd", "CD"
    VHS_TAPE = "vhs", "VHS Tape"
    DVD = "dvd", _("DVD")
    UNKNOWN = "unknown"
   
    groups = {
        "Audio": [VINYL, CD],
        "Video": [VHS_TAPE, DVD],
        "Unknown": [UNKNOWN]
    }

Relatedly, there is pre-pandemic ticket and PR to support dictionaries in Field.choices: https://github.com/django/django/pull/12449 . It could make sense to look at that first, if you'd like to. Enumeration type grouping is kinda orthogonal, but if dict support was added, the "choices" property could use it.

Thanks,

Adam

--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/7d66f6a9-4056-4e2e-ade2-8175994ebd20n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages