2017-07-29 47 views
0

我在django中有一個模型,我們稱之爲product,它被多個purchase實例引用。在Django Rest框架中檢測相關模型的變化

一次購買可用於任何數量的product的項目,來服從於以下約束:

在給定產品的所有購買的所有項目的總金額必須小於項的設置數量上限,每種產品的定義都不相同。

用戶可以爲產品創建一個purchase,並且我想要跟蹤所有購買在任何給定時間涵蓋的物品總數。

這很複雜,因爲用戶可以修改或刪除他們的purchase,從而改變購買的物品總數。

我該如何跟蹤每個product這個數字,並在每次更改purchase時更新它?是否有鉤子可以聽取product的購買並檢測到變化?

purchase型號:

class Purchase(models.Model): 
    items = models.IntegerField(blank=False, default=1) 
    delivery_method = models.CharField(max_length=100, blank=False, default='') 
    #... 
    product = models.ForeignKey('product.Product', 
          related_name='purchases', on_delete=models.CASCADE) 

product型號:

class Product(models.Model): 
    name = models.CharField(max_length=100, blank=False,) 
    items_offered = models.IntegerField(blank=False, default=2) 
    # Items purchased should be the total number 
    # of items in all purchases for this product... 
    # How do I keep it updated? 
    items_purchased = models.IntegerField(blank=False, default=0) 

回答

1

簡單的方法是覆蓋保存,刪除方法,或者使用django signals

class Purchase(models.Model): 
    # ... model definition 
    def update_items_purchased(self, product): 
     purchases = Purchase.objects.filter(product=product) 
     if purchases: 
      total = purchases.aggregate(total=Sum('items')).get('total', 0) 
     else: 
      total = 0 
     product.items_purchased = total 
     product.save() 

    def save(self, *args, **kwargs): 
     super(Purchase, self).save(*args, **kwargs) 
     self.update_items_purchased(self.product) 


    def delete(self, *args, **kwargs): 
     super(Purchase, self).delete(*args, **kwargs) 
     self.update_items_purchased(self.product) 
+0

你能解釋一下'得到( '總',0)'是幹什麼的?我不熟悉字段查找的語法。 「Count」的彙總語句也可以工作嗎? – sonarforte

+0

啊,'get()'是在python字典上作用的;它不是一個查詢集'get()' – sonarforte

+0

對不起,這是錯字錯誤,正確的方式是聚合,我修好了。關於計數它會計算行數,如果在項目中沒有總數可以超過1 –

1

使用post_save信號。

from django.db.models.signals import post_save 
from django.dispatch import receiver 

@receiver(post_save, sender=Purchase) 
def update_purchase_amounts(sender, instance, created, **kwargs): 
    product = Product.objects.get(id=instance.product.id) 
    product.items_purchased += instance.items 
    product.save(update_fields=['items_purchased']) 

我假設purchase.itemsproductPurchase數量。

儘管您可能想要以不同的方式執行此操作,例如爲產品彙總所有Purchase.items字段,以便每次保存Purchase實例時都不會更新購買的金額。因此,也許使用類似:

from django.db.models.aggregates import Sum 
counts = Purchase.objects.filter(product=instance.id).aggregate(Sum('items')) 
product.items_purchased = counts 
product.save(update_fields=['items_purchased']) 
相關問題