2017-04-03 90 views
0

的記錄我有一個Django的模型如下:如何刪除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,因此不是整個計算記錄d。

任何想法該怎麼做?

回答

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) 
+0

當然。非常明顯。 – Boky

相關問題