【问题标题】:How to delete an record from Django model如何从 Django 模型中删除记录
【发布时间】:2017-04-03 09:19:08
【问题描述】:

我有一个 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,因此不是整个计算记录。

知道怎么做吗?

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    删除calculation时删除customer

    def delete(self, *args, **kwargs):
        self.customer.delete()
        super(Calculations, self).delete(*args, **kwargs)
    

    为避免在删除customer 时删除calculation

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

    【讨论】:

      猜你喜欢
      • 2011-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      • 1970-01-01
      相关资源
      最近更新 更多