我正在使用django-oscar,并将一些应用程序分叉为使用自定义模型。
特别是目录模型。默认情况下有产品、产品类型和产品类别。我正在尝试扩展模型,使其具有集合表,并使每个产品都与集合相关联。
我想建立关系,以便在删除集合时删除所有关联的产品,但删除产品不会删除集合。
除了添加一个新的集合表外,我扩展产品表,使其具有一个乘数字段(其中将包含一个用于乘以批发价格的整数……如果有更好的方法,请通知(和集合表的外键。
根据我的理解,一切看起来都很好。这是我的型号.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进行迁移时,在询问了默认值(我稍后会处理(之后,这似乎很好。
然而,当运行migrate时,我得到以下错误输出:
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
。问题是数据库中没有具有此ID的Collection
对象,这就是迁移失败的原因。
你要么需要:
-
在尝试添加覆盖的产品模型之前,使用指定的默认ID创建一个
Collection
对象。 -
使
Collection
的外键可以为null,这样就不需要默认值。