具有自定义模型的分叉 django-oscar 应用程序无法迁移

Forked django-oscar app with custom model unable to migrate

我正在使用 django-oscar 并分叉了一些应用程序以使用自定义模型。

特别是目录模型。默认情况下有产品、产品类型和产品类别。我正在尝试扩展模型以拥有一个集合 table,并让每个产品都与一个集合相关联。

我想建立关系,以便在删除集合时删除所有关联的产品,但删除产品不会删除集合。

除了添加一个新系列 table,我扩展了产品 table 以具有乘数字段(它将包含一个用于乘以批发价的整数...如果有更好的方法请告知)和集合的外键 table.

根据我的理解,一切看起来都不错。这是我的 models.py 来自分叉目录应用程序:

from django.db import models

class Collection(models.Model):
    name = models.CharField(max_length=50)
    prod_category = models.CharField(max_length=50)
    description = models.TextField()
    manufacturer = models.TextField()
    num_products = models.IntegerField()
    image_url = models.URLField()

from oscar.apps.catalogue.abstract_models import AbstractProduct

class Product(AbstractProduct):
    collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
    multiplier = models.DecimalField(max_digits=2, decimal_places=1)

from oscar.apps.catalogue.models import *  

当我通过 manage.py 进行 makemigrations 时,在询问默认值(我稍后会处理的事情)之后似乎没问题。

然而,当 运行 迁移时,我得到以下错误输出:

Running migrations:
  Applying catalogue.0014_auto_20181211_1617...Traceback (most recent call last):
  File "/home/mysite/lib/python3.7/Django-2.1.3-py3.7.egg/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
psycopg2.IntegrityError: insert or update on table "catalogue_product" violates foreign key constraint "catalogue_product_collection_id_e8789e0b_fk_catalogue"
DETAIL:  Key (collection_id)=(1) is not present in table "catalogue_collection".

这是因为我需要添加一个字段吗collection_id?

问题是您指定了一个不存在的默认值。我猜想当要求为迁移指定默认值时,您为集合输入了 1。问题是数据库中没有Collection这个ID的对象,所以迁移失败。

您要么需要:

  1. 在尝试添加覆盖的产品模型之前,使用您指定的默认 ID 创建一个 Collection 对象。

  2. 使 Collection 的外键可为空,这样您就不需要默认值了。