简体   繁体   English

具有HAVING,COUNT和AVG的Django多个注释

[英]Django Multiple Annotations with HAVING, COUNT and AVG

Trying to display TOP 10 business popularity list based on AVG. 试图显示基于AVG的TOP 10商业受欢迎度列表。 Everything works but I'm trying to add additional conditions such as only include businesses HAVING at least 10 votes. 一切正常,但我尝试添加其他条件,例如仅包括至少获得10票的企业。

This works for the AVG with all results: 这对于所有结果均适用于AVG:

Feedvote.objects.filter(site_id=settings.SITE_ID).annotate(
                        voteavg=Avg('feedvote')).order_by('-voteavg')[:10]

Here trying to add HAVING condition for at least 10 votes: 在这里尝试为至少10个投票添加HAVING条件:

Edit: When I run this code below I get nothing, no errors, no values. 编辑:当我在下面运行此代码时,我什么也没有,没有错误,没有值。

Feedvote.objects.filter(city=settings.SITE_ID).annotate(
                       voteavg=Avg('feedvote')).annotate(
                       count_status=Count('business')).filter(
                       count_status__gt=10).order_by('-voteavg')[:10]

It's generating SQL that doesn't return any data. 它正在生成不返回任何数据的SQL。 This is because the second annotate call is being calculated based on the results of the first. 这是因为正在根据第一个注释的结果来计算第二个注释调用。 You could try using to combine them to avoid this. 您可以尝试使用它们来避免这种情况。

Feedvote.objects.filter(city=settings.SITE_ID).annotate(
    voteavg=Avg('feedvote'),
    count_status=Count('business', distinct=True))

我认为您应该将所有注释放在一起:

Feedvote.objects.filter(site_id=settings.SITE_ID).annotate(voteavg=Avg('feedvote'),count_status=Count('business')).filter(count_status__gte=10).order_by('-voteavg')[:10]

Thanks to all that replied! 感谢所有答复! I got it all up and running. 我搞定了一切并开始运行。 The issue was that Django wanted to query the Business table based on the Feedvote table values. 问题是Django想根据Feedvote表值查询Business表。 In SQL I would query the Feedvote table with the Business table as JOIN . 在SQL中,我将查询Feedvote表,并将Business表作为JOIN Django wanted otherwise. Django想要其他方式。

Business.objects.filter(city_id=settings.SITE_ID)
                .annotate(count_status=Count('feedvotes__business'))
                .filter(count_status__gte=10)
                .annotate(voteavg=Avg('feedvotes__feedvote'))
                .order_by('-voteavg')[:10] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM