I have a model Products:
class Products(models.Model):
id = models.PositiveIntegerField(primary_key=True)
name = models.CharField(max_length=255)
image = models.CharField(max_length=255, blank=True, null=True)
status = models.IntegerField()
"""created_by = models.IntegerField(blank=True, null=True)
updated_by = models.IntegerField(blank=True, null=True)"""
created_by = models.ForeignKey('User', db_column='created_by', related_name='created_product')
updated_by = models.ForeignKey('User', db_column='updated_by', related_name='update_product')
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
the mysql shell shows the id field of type:
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
I'm trying to create a ForeignKey to this table in such a way:
class ProductVarieties(models.Model):
id = models.PositiveIntegerField(primary_key=True)
product = models.ForeignKey(Products)
variety = models.CharField(max_length=200, blank=True, null=True)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
on running migrations, I get an error
django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint')
If I do describe product_varieties, I get:
+------------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------------+------+-----+---------+-------+
| id | int(10) unsigned | NO | PRI | NULL | |
| variety | varchar(200) | YES | | NULL | |
| created_at | datetime(6) | YES | | NULL | |
| updated_at | datetime(6) | YES | | NULL | |
| product_id | int(11) | NO | | NULL | |
+------------+------------------+------+-----+---------+-------+
Notice type of
product_idis showingint(11)instead ofint(10) unsigned.
This means django isn't detecting the right field types for the foreign key.