I am new to Python & Django, currently working on food delivery application.
I get the following error in admin when trying to add new Pizza object: "" needs to have a value for field "item_ptr" before this many-to-many relationship can be used.
I have the following: in models.py
class Item(models.Model):
name = models.CharField(max_length=64)
price = models.DecimalField(decimal_places=2,max_digits=10, default=0)
size = models.CharField(choices=SIZES, max_length=64, default="R")
def __str__(self):
return f"{self.name}, {self.size}, ${self.price}"
class Pizza(Item, abstractToppingConfig):
type = models.ForeignKey(pizzaType, on_delete=models.CASCADE)
def save(self, *args, **kwargs):
if not self.id:
newItem = Item(name=self.name, price=self.price, size=self.size)
newItem.save()
self.item_ptr = newItem
super(Pizza, self).save(*args, **kwargs)
def __str__(self):
return f"{self.type} {self.name}, {self.size}"
I've looked up a few of the answers here and understand that the error is occurring due to the parent class not being saved at the time the Pizza object is created. For that purpose, I am trying to override the model save method to store the Item object first and add the relationship, however any of this seems to be working.
Creating and saving the object in Python shell works just fine, but not happening when Pizza object is saved.
Django Version: 2.2.6
Full traceback: https://gist.github.com/Michelle-lele/7b1e60a7a1cf804bd74cfdaae5091c4e