简体   繁体   中英

Django 1.8.2 (using Python 3.4): How is a CharField with choices stored in a MySQL table with an ENUM column?

According to a StackOverflow question , one answer says I can specify a CharField in my Django model that mimics the functionality of a MySQL ENUM column. Suppose I have the following tuple set declared in my models.py module:

HOWDY_EVERYONE = (
    ('0', 'How are you?'),
    ('1', 'How\'s your day?'),
    ('2', 'What are you doing here?')
)

Now I have the following model that simply stores a CharField holding the tuple set I just declared:

class HowdyEveryoneModel(models.Model):
    message_to_everyone = models.CharField(max_length=1, choices=HOWDY_EVERYONE, db_column='Message to Everyone')

Let's say I have a MySQL table that only holds one non-primary-key column, which is 'Message to Everyone.' It is of type ENUM that accepts one of three values just like the values in the HOWDY_EVERYONE tuple set: "How are you?", "How's your day?", or "What are you doing here?"

How is this saved in the MySQL database under the 'Message to Everyone'? Is it simply either "0", "1", or "2", or is it "How are you?", "How's your day?", or "What are you doing here?" In other words, how is a Django CharField, with choices, saved in a MySQL ENUM column?

If it's not possible to have "How are you?", "How's your day?", or "What are you doing here?" in the 'Message to Everyone' column of this MySQL table, what do I need to do to my Django field to make it save as one of these three values when I save my model in the MySQL table?

Django will put into database anything that is on index 0 in tuple of your choice. That means: it will be "0", "1" or "2". If you want it to be 'How are you?' and other, just put it as 0 index in your choice. You can of course repeat it in 1st index (as label).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM