How do I go about specifying and using an ENUM in a Django model?
If it's important to you that the ENUM type is used at the database level, you have three options: Use "./manage.py sql appname" to see the SQL Django generates, manually modify it to use the ENUM type, and run it yourself. If you create the table manually first, "./manage.py syncdb" won't mess with it.
Enum member values are a tuple of arguments to use when constructing the concrete data type. Django supports adding an extra string value to the end of this tuple to be used as the human-readable name, or label . The label can be a lazy translatable string.
Process to get MySQL data So, we need to create the model of the data and implement that model into the db of django. Open 'models.py' and put in the following code. The database table 'students' will be created by the following code. Suppose we have the following records in the 'students' table.
As explained here, enums are stored as values between 0 (no valid value set) and 65,535 that are associated with an enumeration index. The value that is stored in the table is a 2 byte value, not a string.
From the Django documentation:
MAYBECHOICE = ( ('y', 'Yes'), ('n', 'No'), ('u', 'Unknown'), )
And you define a charfield in your model :
married = models.CharField(max_length=1, choices=MAYBECHOICE)
You can do the same with integer fields if you don't like to have letters in your db.
In that case, rewrite your choices:
MAYBECHOICE = ( (0, 'Yes'), (1, 'No'), (2, 'Unknown'), )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With