0

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

  • Someone will provide the answer but what I see as a problem in your code is that you are inheriting `Item` without marking it as `abstract`. See [here](https://docs.djangoproject.com/en/stable/topics/db/models/#abstract-base-classes). You need to add `abstract=True` with `class Meta` to your `Item` class, else it will have a separate table in the database and might not work as intended. – Eray Erdin Jan 12 '20 at 21:32
  • It was an abstract class initially, changed it to current as per https://docs.djangoproject.com/en/2.2/topics/db/models/#multi-table-inheritance as I wanted to be an individual table in the database. And that is the example I followed from docs to override the save method https://docs.djangoproject.com/en/3.0/topics/db/models/#overriding-model-methods – Michelle-lele Jan 13 '20 at 20:26

1 Answers1

0

For anyone, that might face the same issue. I was using clean() method in the abstract class, thus causing the above error.

Django ManyToMany model validation