Boky
Boky

Reputation: 12084

How to delete an record from Django model

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:

Any idea how to do that?

Upvotes: 0

Views: 72

Answers (1)

albar
albar

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

Related Questions