尝试在 MySQL 数据库中设置枚举数据类型时出现问题

Issue while trying to set enum data type in MySQL database

我想做什么?

Django 不支持在 mysql 数据库中设置枚举数据类型。使用下面的代码,我尝试设置枚举数据类型。

错误详情

_mysql.connection.query(self, query) django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'NOT NULL, created_at datetime(6) NOT NULL, user_id bigint NOT NULL)' at line 1")

我错过了什么吗?

枚举class所有选项

class enumTokenTypes(models.TextChoices):
    Registration = "Registration"
    ForgotPassword = "Forgot Password"

模型中的用户令牌class

class tblusertokens(models.Model):
    token_id = AutoField(primary_key=True)
    token_type = EnumField(max_length=20, choices=enumTokenTypes.choices)
    created_at = DateTimeField(auto_now_add=True, blank=True)
    user = ForeignKey(tblusers, on_delete = models.CASCADE)    

用户令牌在迁移中创建模型

class EnumField(CharField):
    def db_type(self, connection):
        return "enum"


migrations.CreateModel(
    name='tblusertokens',
    fields=[
        ('token_id', models.AutoField(primary_key=True, serialize=False)),
        ('token_type', clientauth.models.EnumField(choices=[('Registration', 'Registration'), ('Forgot Password', 'Forgotpassword')], max_length=20)),
        ('created_at', models.DateTimeField(auto_now_add=True)),
        ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='clientauth.tblusers')),
    ],
)

赏金问题

为函数设置 2 个参数以传递逗号分隔值和默认值。

您可以打印出该迁移的 sql 以具体查看错误,但是将 db_type 定义为 return "enum" 绝对不是正确的方法它。

    ('token_type', CharField(choices=enumTokenTypes.choices, max_length=22)),

Enumeration types 上的文档推荐的语法是否出于某种原因不适合您?

数据类型应该是 enum('Registration', 'Forgot Password') 而不是 enum.

class EnumField(CharField):

    def db_type(self, connection):
        if connection.vendor == 'mysql':
            return 'enum({0})'.format(','.join("'%s'" % value for value, label in self.choices))
        return super().db_type(connection)

参考:https://dev.mysql.com/doc/refman/8.0/en/enum.html

数据库默认值

虽然在上面的 MySQL 8.0 文档中没有明确提及,但您也可以指定数据库默认值。

class EnumField(CharField):

    def __init__(self,  *args, **kwargs):
        self.db_default = kwargs.pop('db_default', None)
        super().__init__(*args, **kwargs)

    def db_type(self, connection):
        if connection.vendor == 'mysql':
            if self.db_default is not None:
                return "enum({0}) DEFAULT '{1}'".format(','.join("'%s'" % value for value, label in self.choices), self.db_default)
            return 'enum({0})'.format(','.join("'%s'" % value for value, label in self.choices))
        return super().db_type(connection)

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        if self.db_default:
            kwargs['db_default'] = self.db_default
        return name, path, args, kwargs

用法:

token_type = EnumField(max_length=20, choices=enumTokenTypes.choices, db_default=enumTokenTypes.ForgotPassword)

关于deconstruct()方法

来自 https://docs.djangoproject.com/en/3.2/howto/custom-model-fields/#field-deconstruction:

The counterpoint to writing your __init__() method is writing the deconstruct() method. It’s used during model migrations to tell Django how to take an instance of your new field and reduce it to a serialized form - in particular, what arguments to pass to __init__() to re-create it.

If you add a new keyword argument, you need to write code in deconstruct() that puts its value into kwargs yourself.

对赏金问题的回应

设置默认值:在EnumField中添加默认参数。在下面的示例中,我将 enumTokenTypes Registration 设置为其默认值。通过示例

查看 Django documentationenum 实施
     class tblusertokens(models.Model):
          token_id = AutoField(primary_key=True)
          token_type = EnumField(max_length=20, choices=enumTokenTypes.choices, default=enumTokenTypes.Registration )
          created_at = DateTimeField(auto_now_add=True, blank=True)
          user = ForeignKey(tblusers, on_delete = models.CASCADE)