Django.db.utils.IntegrityError: and django.db.utils.OperationalError:
raise integrityerror( django.db.utils.integrityerror: the row in table 'hazeapp_orderitem' with primary key '1' has an invalid foreign key: hazeapp_orderitem.product_id contains a value '5' that does not have a corresponding value in hazeapp_newarrival.id.enter image description here
I am trying to build 2 different models that include different product with their prices, name etc and render those two model products in two different template using for loop. But while creating an OrderItem model which includes both above foreign model leads to integrity error mostly. The code i tried was:
class NewArrival(models.Model):
name = models.CharField(max_length=200, null=False, blank=True)
price = models.FloatField(default=0)
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.name
class Collection(models.Model):
name = models.CharField(max_length=200, null=False, blank=True)
price = models.FloatField(default=0)
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.name
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False, null=True, blank=False)
transaction_id = models.CharField(max_length=200, null=True)
def __str__(self):
return str(self.id)
class OrderItem(models.Model):
collection = models.ForeignKey(Collection, on_delete=models.SET_NULL, blank=True, null=True)
newarrival = models.ForeignKey(NewArrival, on_delete=models.SET_NULL, blank=True, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
quantity = models.IntegerField(default=0, null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
@property
def get_total(self):
total = 0
if self.collection:
total += self.collection.price * self.quantity
if self.newarrival:
total += self.newarrival.price * self.quantity
return total