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)
2
  • Possible duplicate of what does on_delete do on Django models? Commented Feb 16, 2018 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. Commented Feb 16, 2018 at 21:26

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.