3

I am trying to work what is the correct usage of the models.cascade statement. I have two models Cart and Entry. If I delete an Entry the deletion is not updated on the Cart Entry. I have checked this via the admin interface. My models.py is as below:

class Cart(models.Model):
    user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
    count = models.PositiveIntegerField(default=0)
    total = models.DecimalField(default=0.00, max_digits=10, decimal_places=2)
    updated = models.DateTimeField(auto_now=True)
    timestamp = models.DateTimeField(auto_now_add=True)

    objects = CartManager()

    def __str__(self):
        return "Cart:{} User:{} Items:{} Total:£{}".format(self.id, self.user, self.count, self.total)

class Entry(models.Model):
    product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE)
    cart = models.ForeignKey(Cart, null=True, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField(default=0)
Rutnet
  • 1,533
  • 5
  • 26
  • 48
  • Possible duplicate of [what does on\_delete do on Django models?](https://stackoverflow.com/questions/38388423/what-does-on-delete-do-on-django-models) – Sphinx Feb 16 '18 at 21:18
  • model.cascade isn't actually getting rid of the record for me. So if I delete an entry, the cart is not updated. – Rutnet Feb 16 '18 at 21:26

2 Answers2

1

I believe you have your concept of the cascade backwards. Based on your model, your Entry will be deleted when you call delete on the Cart for the foreign key relationship. If you wanted the deletion to work in reverse you would need to add some additional code to handle that. You could look at Django cascade delete on reverse foreign keys for some ideas on how to implement that (if that is what you need).

Studybuffalo
  • 399
  • 4
  • 8
0

Because you're not associating Entry and Cart,Just set the Entry ForeignKey and use on_delete. When you delete an Cart the deletion, the Entry associated with it will be deleted.