pythondjangopython-3.9django-3.2

Issue while creating Foreign Key constraint


Issue Details

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

What am I doing?

I created a tinyint auto increment field below but when referencing it in another table causing issue.

Code in Model file

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)
    

Code in Migration File

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')),
    ],
),

Bounty Question

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

This line in above code doesn't set cascade delete database side. I checked docs but could not find one that set the cascade delete. Can you suggest one?


Solution

  • Override rel_db_type to return similar to db_type without AUTO_INCREMENT.

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

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