How we do Enums #393
devxpy
announced in
Programming Guide
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
If you ever find yourself trying to define an enum but you want multiple fields for the value, use this pattern.
Start by defining a
NamedTuple
of your desired fieldsThen inherit from both the named tuple you defined and
Enum
. This works because the enum constructor accepts tuples as*args
This makes it so that you can directly access the fields of the enum from the enum without doing
enum.value.field
:It works as expected with UI selectboxes, given you have defined a
label
field:This is preferred over django's
TextChoices
andIntegerChoices
too, just add adb_value
to your tuple and provide thedb_choices
andfrom_db_value
methods:And then in your model:
And to read these values from a model:
Beta Was this translation helpful? Give feedback.
All reactions