Django ForeignKey field type

Viewed 2757

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_id is showing int(11) instead of int(10) unsigned.

This means django isn't detecting the right field types for the foreign key.

1 Answers

If this is what happened:

  1. Your models are unmanaged (managed = False in Meta).
  2. You have created the initial migration for the unmanaged target model Products.
  3. You've then altered the primary key type.
  4. Now you're trying to create the foreign key.

Then you need to delete the migration mentioned in 2) and then recreate it. Only then the correct type is passed to the foreign key.

Note that this may still go wrong, if PositiveIntegerField has an INT(NOT_10) as MySQL db representation.

Related