2012-03-01 53 views
2

我正在进行一系列查询以获取查询集的过滤变体。有没有更简单的方法来做到这一点,我不打数据库6次,而只是使用初始调用?在Django中合并查询

data['os']['today'] = Page.objects.all() 
data['os']['pro'] = Page.objects.filter(premium_plan=PlanType.PRO).count() 
data['os']['yesterday'] = Page.objects.filter(created__lt=within_last_day).count() 
data['os']['week'] = Page.objects.filter(created__lt=within_last_week).count() 
data['os']['new_pro'] = Page.objects.filter(upgrade__cancelled_date__isnull=True, upgrade__activated_date=within_last_day) 
data['os']['new_top_pages'] = Page.objects.filter(created__gt=within_last_day).extra(select={'total_fans':'facebook_count + twitter_count'}, order_by=('-total_fans',))[:10] 

回答

0

,如果你让所有的网页:

pages = Page.objects.all() # Page.objects.select_related() if we want filtering on related objects fields 

然后你就可以获取其他类型的网页,无需额外DB查询:

# it will not call the database 
data['os']['yesterday'] = pages.filter(created__lt=within_last_day).count() 
data['os']['week'] = pages.filter(created__lt=within_last_week).count() 
... 

如果通过过滤器的方法获得一个页面,随后调用过滤器将与第一次读取集一起工作:

pages = Page.objects.filter(id__in=(1,2,3)) # we have pages in db with ids in 1,2,3,4,5 
pages_additional = pages.filter(condition) #Here we are working with objects with ids 1,2,3 

如果起初您不获取所有记录(Page.objects.all()),则无法获取未包含在第一个读取集中而没有任何附加查询的附加数据。