Trying to display TOP 10 business popularity list based on AVG. Everything works but I'm trying to add additional conditions such as only include businesses HAVING at least 10 votes.
This works for the AVG with all results:
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:
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. 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. In SQL I would query the Feedvote
table with the Business
table as JOIN
. Django wanted otherwise.
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.