2009-09-30 63 views
2

我可以將這兩個查詢集鏈接成一個嗎?Django ORM:將聚集的查詢集鏈接成一個

qs1 = OrderTicket.objects.filter(date__gt=datetime.date(2009, 1, 1), date__lt=datetime.date(2009, 1, 30)).values('order_type').annotate(value_1 = Sum('gbp_value')).order_by('order_type'), 
qs2 = OrderTicket.objects.filter(date__gt=datetime.date(2009, 2, 1), date__lt=datetime.date(2009, 2, 30)).values('order_type').annotate(value_2 = Sum('gbp_value')).order_by('order_type'), 

我只想要的是value_1和value_2列。 Q對象不是我所需要的。也許ORM不支持這個。

回答

1

我會建議使用Q objects更換你的過濾器date__gt和date__lt

例(未測試):

qs1 = OrderTicket.objects 
    .filter( Q(date__gt=datetime.date(2009, 1, 1), date__lt=datetime.date(2009, 1, 30)) 
      | Q(date__gt=datetime.date(2009, 2, 1), date__lt=datetime.date(2009, 2, 30)) 
      ) 
    .values('order_type').annotate(value_1 = Sum('gbp_value')).order_by('order_type') 

這將返回兩個日期,你正在尋找。

+0

感謝湯姆但是這不是我所期待的。 value_1和value_2會將其所有月份的所有gbp_values相加。我如何鏈接這兩個聚合查詢集? – orwellian 2009-09-30 08:23:50

2

您可以使用|和&運營商:

# You can combine queries with & and |. 
>>> s1 = Article.objects.filter(id__exact=1) 
>>> s2 = Article.objects.filter(id__exact=2) 
>>> s1 | s2 
[<Article: Area woman programs in Python>, <Article: Second article>] 
>>> s1 & s2 
[] 

來源http://www.djangoproject.com/documentation/models/basic/

+0

這是一個很好的小處理! – jathanism 2010-01-22 22:21:58