Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying a mySQL ENUM in a Django model

How do I go about specifying and using an ENUM in a Django model?

like image 427
Steve Avatar asked Aug 21 '08 23:08

Steve


People also ask

Which of the following is the correct way to specify ENUM in Django?

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.

What is ENUM in Django?

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.

How fetch data from MySQL to Django?

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.

How is ENUM stored in MySQL?

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.


1 Answers

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'), ) 
like image 157
fulmicoton Avatar answered Oct 04 '22 15:10

fulmicoton