Reputation: 744
I am using django-oscar and forked some of the apps to use a custom model.
Specifically with the catalogue model. By default there are products, product types and product categories. I am trying to extent the model to have a collections table, and to have each product be associated with a collection.
I want to make the relationship so that when a collection is deleted all associated products are deleted, but so that deleting a product does not delete a collection.
Aside from adding a new collection table, I extent the product table to have a multiplier field (which will contain an integer used to multiply the wholesale price...if there is a better way to do this please inform) and a foreign key to the collections table.
Based on my understanding everything looks good. This is my models.py from the forked catalogue app:
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 *
When I do makemigrations via manage.py, after asking for default values (something I will deal with later) it seems fine.
When running migrate however, I get the following error output:
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".
Is this because I need to add a field collection_id?
Upvotes: 0
Views: 312
Reputation: 31474
The problem is that you have specified a default value that doesn't exist. I am guessing that when asked to specify default values for the migration, you entered 1
for the collection. The problem is that there is no Collection
object with such an ID in the database, which is why the migration fails.
You either need to:
Create a Collection
object with the default ID you specified before attempting to add the overridden product model.
Make the foreign key to Collection
nullable, so that you don't need a default value.
Upvotes: 1