2017-03-14 119 views
0

請參考我的模型(3型號:變體,交易和廣告系列)。過濾器相關型號

我想獲得一個變體及其相關交易的列表,其活動開始日期是今天。

我已經能夠過濾廣告系列的開始日期,但是,返回的交易列表未被過濾。

def get_queryset(self): 

    """ 

     Override get_queryset to cater for dynamic filtering 

    """ 

    date_filters = [] 

    from_date = self.request.GET.get('from', None) 

    if from_date is not None and len(from_date) > 0: 
     date_filters.extend([Q(deal_set__campaign_start_date__gte=parse_date(from_date)),]) 
    else: 
     date_filters.extend([Q(deal_set__campaign_start_date__gte=now()),]) 

    to_date = self.request.GET.get('to', None) 

    if to_date is not None and len(to_date) > 0: 
     date_filters.extend([Q(deal_set__campaign_end_date__lte=parse_date(to_date)),]) 

    return Variant.objects.filter(*date_filters).distinct() 

class Variant(BaseModel): 

    """ 

    Product model 

    """ 

    variant_id = models.AutoField(primary_key=True) 
    unit = models.ForeignKey(Unit, on_delete=models.CASCADE) 
    value = models.DecimalField(max_digits=3, decimal_places=2, default=Decimal('0.0')) 
    product = models.ForeignKey(Product, on_delete=models.CASCADE) 

class Deal(BaseModel): 

    """ 

    Deal model 

    """ 

    deal_id = models.AutoField(primary_key=True) 
    price = models.DecimalField(max_digits=4, decimal_places=2) 
    variant = models.ForeignKey(Variant, on_delete=models.CASCADE) 
    campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE) 

class Campaign(BaseModel): 

    """ 

    Campaign model 

    """ 

    campaign_id = models.AutoField(primary_key=True) 
    start_date = models.DateField(default=now()) 
    end_date = models.DateField(default=now()) 
    store = models.ForeignKey(Store, on_delete=models.CASCADE) 
+0

您應該發佈代碼,在其中顯示您已嘗試的內容。 –

+0

這個怎麼樣:'today = date.today()'和'Variant.objects.filter(deal__campaign__start_date = today)'? –

回答

0

您是否想要所有變體或僅有變體具有今天活動開始日期的交易?

對於後者,應該是這樣的:

from datetime import date 

Variant.objects.filter(deal_set__campaign__start_date=date.today()) 

如果需要用select_related結合起來。

+0

它應該是'過濾器(處理__...',而不是'過濾器(處理__...'),最好的問候! –

+0

謝謝!所有優惠正在退還(不僅僅是被活動開始日期過濾的) – Neelesh

+0

@Neelesh是的,過濾器僅適用於Variant類,您需要使用'myvariant.deal_set.filter(campaign__start_date = date.today())'來獲得正確的交易。我認爲您不能在單個查詢。 –