Enum field in MySQL

Question:

In MySQL there are several types of data, char, varchar int, boolean as you already know.

But it also has the Enum type that in SQL we create the table as follows:

CREATE TABLE person(
  id int.....
  name varchar(50),
  
  and

   Married Enum(Yes,No)

)

My goal is, when I’m creating the models in Django (Python) to be able to create the tables in MySQL I can automatically create this type of field as well.

I tried like this:

from django.db import models
from enum import enum

class options(Enum):
    Yes = "Yes"
    No = "No"

class Customer(models.Model) :
                
    name = models.CharField(max_length=200)
    docto = models.CharField(max_length=14)
    age = models.IntegerField(default=0)
    username = models.CharField(max_length=20)
    password = models.CharField(max_length=20)
        
    block = models.CharField(
        max_length=3,
        choices=[(tag, tag.value) for tag in options],
        default= 'No'
    )
    
    def __str__(self):
        return self.name
        

Create the field in MySQL creates but creates as VARCHAR(3) and not as enum.

Can Django do this? How would it be?

I wouldn’t like to have to create the tables directly in the database,

Asked By: Carlos Rocha

||

Answers:

There is currently a python package on github called django-mysql based on adding these, though I’ve not looked into exactly how they’re implemented but by reading the documenation of this part of this package, I found out it implement an enum field on database you can see the below example to see how you can use this package.

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)
Answered By: Javad Nikbakht
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.