Opened 5 years ago

Last modified 5 years ago

#31261 closed New feature

Add support for defining Enum fields with dict, tuple, set and list values — at Initial Version

Reported by: Tom Forbes Owned by: nobody
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: Shai Berger, pope1ni Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

As per the discussion on this forum post: https://forum.djangoproject.com/t/moving-to-django-3-0s-field-choices-enumeration-types/970/8

It would be good to support two fairly common use cases with Enums: defining groups of related values (groups), and defining grouping for use with specific widgets.

One way to enable both of these would be to simply special-case enum values with dict, tuple, set and list values:

class MoonMissions(Enum):
    APOLLO_10 = 1
    APOLLO_11 = 2
    EXPLORER_33 = 3

    FAILED_MISSIONS = {EXPLORER_33}
    SUCCESSFUL_MISSIONS = (APOLLO_10, APOLLO_11)
    
    SUCCESS_GROUPING = {
        "Failed": FAILED_MISSIONS,
        "Successful": SUCCESSFUL_MISSIONS
    }
   
    COUNTRY_GROUPING = [
         ["USA", [APOLLO_10, APOLLO_11, EXPLORER_33]]
    ]

Now a user can do:

SomeModel.objects.filter(mission__in=MoonMissions.FAILED_MISSIONS)
enum_form_field.value in MoonMissions.SUCCESSFUL_MISSIONS
models.IntegerField(choices=MoonMissions.COUNTRY_GROUPING)

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top