EnumField¶
Using a CharField with a limited set of strings leads to inefficient data
storage since the string value is stored over and over on disk. MySQL’s
ENUM type allows a more compact representation of such columns by storing
the list of strings just once and using an integer in each row to refer to
which string is there. EnumField allows you to use the ENUM type with
Django.
- class django_mysql.models.EnumField(choices, **kwargs)¶
A subclass of Django’s
Charfieldthat uses a MySQLENUMfor storage.choicesis a standard Django argument for any field class, however it is required forEnumField. It can either be a list of strings, or a list of two-tuples of strings, where the first element in each tuple is the value used, and the second the human readable name used in forms. The best way to form it is with Django’sTextChoicesenumeration type.For example:
from django.db import models from django_mysql.models import EnumField class BookCoverColour(models.TextChoices): RED = "red" GREEN = "green" BLUE = "blue" class BookCover(models.Model): colour = EnumField(choices=BookCoverColour.choices)
Warning
It is possible to append new values to
choicesin migrations, as well as edit the human readable names of existing choices.However, editing or removing existing choice values will error if MySQL Strict Mode is on, and replace the values with the empty string if it is not.
Also the empty string has strange behaviour with
ENUM, acting somewhat likeNULL, but not entirely. It is therefore recommended you ensure Strict Mode is on.