marcotcr / lime

Lime: Explaining the predictions of any machine learning classifier
BSD 2-Clause "Simplified" License
11.64k stars 1.81k forks source link

Enum field in MySQL #686

Closed carcleo closed 2 years ago

carcleo commented 2 years ago

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,

carcleo commented 2 years ago
from django.db import models
from enum import Enum
#pip install django-mysql
from django_mysql.models import EnumField

class options(models.TextChoices):
    Sim = "Sim"
    Não = "Não"

class Cliente(models.Model) :

    block   = EnumField(choices=options.choices, default= 'Não')

    def __str__(self):
        return self.name