在Django中组合查询

时间:2012-03-01 01:35:47

标签: django django-queryset

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

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]

1 个答案:

答案 0 :(得分:0)

如果您获得所有页面:

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

然后你可以在没有额外数据库查询的情况下获取其他类型的页面:

# 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()),则无法获得未包含在第一个提取集中的其他数据而无需任何其他查询。

相关问题