Django ForeignKey字段类型

时间:2017-09-20 08:44:15

标签: python mysql django django-models

我有一个型号产品:

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)

mysql shell显示类型为

的id字段
| id         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |

我试图以这种方式为这个表创建一个ForeignKey:

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)

关于运行迁移,我收到错误 django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint')

如果我describe product_varieties,我得到:

+------------+------------------+------+-----+---------+-------+
| 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    |       |
+------------+------------------+------+-----+---------+-------+
  

product_id的通知类型显示int(11)而不是int(10) unsigned

这意味着django没有检测到外键的正确字段类型。

1 个答案:

答案 0 :(得分:1)

如果发生这种情况:

  1. 您的模型不受管理(在Meta中managed = False)。
  2. 您已经为非托管目标模型Products创建了初始迁移。
  3. 然后您更改了主键类型。
  4. 现在您正在尝试创建外键。

然后,您需要删除2)中提到的迁移,然后重新创建它。只有这样,正确的类型才会传递给外键。

请注意,如果PositiveIntegerField具有INT(NOT_10)作为MySQL数据库表示形式,这可能仍然会出错。

相关问题