【发布时间】:2018-03-01 05:37:48
【问题描述】:
我有一个模型产品:
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 没有检测到正确的外键字段类型。
【问题讨论】:
-
你为什么把你的id字段设为PositiveIntegerFields? Django 不会检测到它们是自动增量,因此您将在更新和插入时遇到问题。
-
那是因为使用
models.AutoField会创建带有int(11)而不是int(10) unsigned的主键。我的表中已经有带有int(10) unsigned的表。我希望能够与他们建立 ForeignKey 关系。 -
为什么不使用默认 ID?如果您想将 id 用作其他表的键 - 您可以进行迁移,因此任何信息都不会丢失。
-
伙计们,我认为您没有理解这里的重点。如果我将
AutoField用作主键,则在创建foreign keys时int(11) and int(10) unsigned之间存在类型冲突。 Django 不允许我在创建foreign keys时指定要使用的字段类型,mysql不允许我从int(11)到int(10) unsigned创建foreign keys。
标签: python mysql django django-models