【问题标题】:Forked django-oscar app with custom model unable to migrate具有自定义模型的分叉 django-oscar 应用程序无法迁移
【发布时间】:2018-12-14 18:00:37
【问题描述】:

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

特别是目录模型。默认有产品、产品类型和产品类别。我试图扩展模型以拥有一个集合表,并使每个产品与一个集合相关联。

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

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

根据我的理解,一切看起来都不错。这是我来自分叉目录应用程序的 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 时,在询问默认值(我稍后会处理)之后似乎很好。

但是,在运行 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 吗?

【问题讨论】:

    标签: python django django-oscar


    【解决方案1】:

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

    您需要:

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

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

    【讨论】:

    • 啊,谢谢!我不知道它连接到默认值。使外键可以为空有什么缺点,是不好的做法还是类似的?
    • 不,没有缺点。更多的是关于如何使用您的数据的问题 - 即,您是否要求产品属于某个集合。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 2022-11-10
    • 2013-05-13
    • 2021-11-27
    • 2015-05-25
    • 1970-01-01
    相关资源
    最近更新 更多