Saturday, 9 October 2021

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


from Issue while creating Foreign Key constraint

No comments:

Post a Comment