我有一个Django模型如下:
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)
和客户模型如下:
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)
我想从客户那里删除一条记录。我这样做:
Customer.objects.filter(id=some_id).delete()
但这会删除customer
和calculation
。
我应该使用on_delete
,因此类似于:
customer = models.ForeignKey(to=Customer, null=True, blank=True, on_delete=models....)
但是,我想要的是:
calculation
,那么我也想删除客户customer
删除记录,我只想删除客户并删除计算中的customer_id
,而不是整个计算记录。知道怎么做吗?
答案 0 :(得分:1)
删除customer
时删除calculation
:
def delete(self, *args, **kwargs):
self.customer.delete()
super(Calculations, self).delete(*args, **kwargs)
为避免在删除calculation
时删除customer
:
customer = models.ForeignKey(to=Customer, null=True, blank=True, on_delete=models.SET_NULL)