Reputation: 12084
I have an Django model as follows:
class Calculations(models.Model):
category = models.CharField(max_length=127)
make = models.CharField(max_length=127)
model = models.CharField(max_length=127)
customer = models.ForeignKey(to=Customer, null=True, blank=True)
data = models.TextField(null=True, blank=True)
and customer model as follows:
class Customer(models.Model):
title = models.CharField(max_length=4, null=True)
firstname = models.CharField(max_length=30)
lastname = models.CharField(max_length=30)
email = models.EmailField(null=True)
address = models.CharField(max_length=80)
I want to delete one record from the customer. I do it as follows:
Customer.objects.filter(id=some_id).delete()
But that deletes customer
and also calculation
.
I should probably use on_delete
, thus something like:
customer = models.ForeignKey(to=Customer, null=True, blank=True, on_delete=models....)
But, what I want is:
calculation
then I want to delete also the customer, customer
I want only that the customer is deleted and that the customer_id
from calculations is deleted, thus not the whole calculation record.Any idea how to do that?
Upvotes: 0
Views: 72
Reputation: 3100
To delete the customer
when you delete a calculation
:
def delete(self, *args, **kwargs):
self.customer.delete()
super(Calculations, self).delete(*args, **kwargs)
To avoid deleting the calculation
when you delete a customer
:
customer = models.ForeignKey(to=Customer, null=True, blank=True, on_delete=models.SET_NULL)
Upvotes: 1