创建外键约束时出现问题

Issue while creating Foreign Key constraint

问题详情

'Can't create table django.clientauth_tblusers (errno: 150 "Foreign key constraint is incorrectly formed")')

我在做什么?

我在下面创建了一个 tinyint 自动递增字段,但在另一个 table 中引用它时导致问题。

模型文件中的代码

class TinyIntField(AutoField):
    def db_type(self, connection):
        return "tinyint(3) AUTO_INCREMENT"

class tblroles(models.Model):
    role_id = TinyIntField(primary_key=True, verbose_name = "role_id")
    name = CharField(max_length = 20)

class tblusers(models.Model):
    user_id = BigAutoField(primary_key=True)
    role = ForeignKey(tblroles, on_delete = models.CASCADE)
    

迁移文件中的代码

migrations.CreateModel(
    name='tblroles',
    fields=[
        ('role_id', clientauth.models.TinyIntField(primary_key=True, serialize=False, verbose_name='role_id')),
        ('name', models.CharField(max_length=20))
    ],
),
migrations.CreateModel(
    name='tblusers',
    fields=[
        ('user_id', models.BigAutoField(primary_key=True, serialize=False)),
        ('role', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='clientauth.tblroles')),
    ],
),

赏金问题

on_delete=django.db.models.deletion.CASCADE, to='clientauth.tblroles'

上面代码中的这一行没有设置级联删除数据库端。我检查了文档,但找不到设置级联删除的文档。你能推荐一个吗?

rel_db_type 覆盖为 return,类似于没有 AUTO_INCREMENTdb_type

class TinyIntField(AutoField):
    def db_type(self, connection):
        return "tinyint(3) AUTO_INCREMENT"

    def rel_db_type(self, connection):
        return "tinyint(3)"

参考:https://docs.djangoproject.com/en/3.2/howto/custom-model-fields/#custom-database-types