Django ForeignKey 字段类型

3

我有一个模型叫做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)

MySQL shell 显示类型为 id 的字段:

| id         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |

我想以这种方式创建一个外键:

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
你为什么将id字段设置为PositiveIntegerFields?Django无法检测到它们是自增的,因此在更新和插入时会出现问题。 - Daniel Roseman
这是因为使用 models.AutoField 会创建带有 int(11) 而不是 int(10) unsigned 的主键。我已经在我的表中有了 int(10) unsigned 类型的表。我想能够与它们建立外键关系。 - Ishan Khare
为什么不使用默认的ID?如果您想将ID用作其他表的键 - 您可以进行迁移,以便不会丢失任何信息。 - Oleksiy
1
伙计们,我觉得你们没有理解重点。如果我在主键上使用AutoField,则在创建外键时会出现int(11)和int(10) unsigned之间的类型冲突。Django不允许我指定创建外键时要使用的字段类型,而mysql也不允许我从int(11)int(10) unsigned创建外键 - Ishan Khare
1个回答

1
如果出现以下情况:
  1. 您的模型是未管理的(在 Meta 中为 managed=False)。
  2. 您已为未管理的目标模型 Products 创建了初始迁移。
  3. 然后您更改了主键类型。
  4. 现在您正在尝试创建外键。
那么您需要删除步骤 2 中提到的迁移,然后重新创建它。只有这样才能将正确的类型传递给外键。
请注意,如果 PositiveIntegerField 在 MySQL 数据库中表示为 INT(NOT_10),则仍可能出现问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接