2016-08-01 45 views
1

我想創建一個模型,經理對我的購買模式:Django的查詢集 - 在相關對象的布爾值篩選對象

class Purchase(models.Model) 
    number = models.IntegerField 

class InventoryLog(models.Model) 
    purchase = models.ForeignKey(Purchase) 
    sold_out = models.BooleanField(default=false) 

我想我的模型管理器返回任何Purchase對象不相關到InventoryLog對象與值True

有沒有辦法處理這與查詢集,Q對象或F對象,或者我需要訴諸for循環?

回答

2

我相信Purchase.objects().exclude(inventorylog__sold_out=True)會這樣做。

+0

很棒!謝謝! –

0

如果你想使用管理的模型,這個怎麼樣:更新感謝Peter DeGlopper評論

#models.py 
class PurhchaseNotSoldOut(models.Manager): 
    def get_queryset(self): 
     return super(PurchaseNotSoldOut, self).get_queryset()\ 
          .exclude(purhcase_logs__sold_out=True) 

class Purchase(models.Model) 
    number = models.IntegerField 

    notSoldOut = PurchaseNotSoldOut() 

class InventoryLog(models.Model) 
    purchase = models.ForeignKey(Purchase, related_name='purchase_logs') 
    sold_out = models.BooleanField(default=false) 

代碼示例

+1

1)您的'filter'子句中的語法不正確,請使用'__'來跟蹤過濾器中的fk關係。 2)這兩個查詢不等價,因爲'Purchase'可以有許多'InventoryLog'。 'filter(purchase_log__sold_out = False)'發現至少有一個沒有售罄,'exclude()'排除那些售罄的人(所以它只返回那些沒有售罄的人)。 –

+0

覆蓋'get_queryset'有什麼好處,而不是僅僅返回一個新的? –

+0

覆蓋'get_queryset'就是您通常如何製作自定義管理器:https://docs.djangoproject.com/en/1.9/topics/db/managers/#modifying-a-manager-s-initial-queryset –