Opened 5 years ago

Closed 5 years ago

Last modified 5 years ago

#31261 closed New feature (needsinfo)

Add support for defining models.Choices fields with dict, tuple, set and list values. — at Version 1

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 (last modified by Mariusz Felisiak)

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(models.IntegerChoices):
    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 (1)

comment:1 by Mariusz Felisiak, 5 years ago

Description: modified (diff)
Resolution: needsinfo
Status: newclosed
Summary: Add support for defining Enum fields with dict, tuple, set and list valuesAdd support for defining models.Choices fields with dict, tuple, set and list values.

Thanks for this ticket, however I'm not sure if that's feasible because we support subclasses of Choices for a data type other that int or str (see examples). This can be break backward compatibility. I would be very happy to evaluate a patch, but without breaking a current behavior.

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