如何从Django模型中删除记录

时间:2017-04-03 09:19:09

标签: django django-models

我有一个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()

但这会删除customercalculation

我应该使用on_delete,因此类似于:

customer = models.ForeignKey(to=Customer, null=True, blank=True, on_delete=models....)

但是,我想要的是:

  • 如果我删除calculation,那么我也想删除客户
  • 但如果我从customer删除记录,我只想删除客户并删除计算中的customer_id,而不是整个计算记录。

知道怎么做吗?

1 个答案:

答案 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)