Fixed #27910 -- Added enumeration helpers for use in Field.choices.

These classes can serve as a base class for user enums, supporting
translatable human-readable names, or names automatically inferred
from the enum member name.

Additional properties make it easy to access the list of names, values
and display labels.

Thanks to the following for ideas and reviews:

Carlton Gibson, Fran Hrženjak, Ian Foote, Mariusz Felisiak, Shai Berger.

Co-authored-by: Shai Berger <shai@platonix.com>
Co-authored-by: Nick Pope <nick.pope@flightdataservices.com>
Co-authored-by: Mariusz Felisiak <felisiak.mariusz@gmail.com>
This commit is contained in:
Shai Berger 2018-12-31 19:57:35 +02:00 committed by Mariusz Felisiak
parent 25706d7285
commit 72ebe85a26
11 changed files with 554 additions and 4 deletions

View file

@ -198,6 +198,19 @@ ones:
>>> p.get_shirt_size_display()
'Large'
You can also use enumeration classes to define ``choices`` in a concise
way::
from django.db import models
class Runner(models.Model):
MedalType = models.TextChoices('MedalType', 'GOLD SILVER BRONZE')
name = models.CharField(max_length=60)
medal = models.CharField(blank=True, choices=MedalType.choices, max_length=10)
Further examples are available in the :ref:`model field reference
<field-choices>`.
:attr:`~Field.default`
The default value for the field. This can be a value or a callable
object. If callable it will be called every time a new object is