views:

281

answers:

2

Can I chain these two querysets into one?

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'),

All I want is the value_1 and value_2 columns. Q objects are not what I need. Maybe the ORM does not support this.

+1  A: 

I would suggest using Q objects to replace your filter for date__gt and date__lt

Example (not tested):

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')

This should return both the dates you are looking for.

Tom Leys
Thanks Tom but that is not what I am looking for. value_1 and value_2 sums all gbp_values per their respective month. How can I chain those two aggregate querysets?
orwellian
+1  A: 

You can combine querysets using the | and & operators:

# 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
[]

Source http://www.djangoproject.com/documentation/models/basic/

PhilGo20
That's a nice little treat right there!
jathanism