gpt4 book ai didi

python - 带有 JOIN 和 GROUP BY SQL 查询的 Django COUNT

转载 作者:行者123 更新时间:2023-11-29 05:23:57 30 4
gpt4 key购买 nike

此 SQL 查询的正确 Django View 和 HTML 是什么?:

SELECT 
hood.`hood`,
COUNT(business.`id`) AS TOTAL
FROM
`hood`
JOIN business
ON hood.`id` = business.`hood_id`
WHERE business.`city_id` = 8
GROUP BY hood.`id`
ORDER BY TOTAL DESC
LIMIT 5 ;

我的模型是:

class Hood(models.Model):
name = models.CharField(max_length=50, db_column='hood')
slugname = models.SlugField(max_length=50, blank=True)
city = models.ForeignKey('City', related_name='hoods')
location = models.ForeignKey('Location', related_name='hoods')
switch = models.SmallIntegerField(null=True, blank=True, default='1')
class Meta:
db_table = 'hood'


class Business(models.Model):
name = models.CharField(max_length=50, db_column='name', blank=True)
slugname = models.SlugField(max_length=50, blank=True)
city = models.ForeignKey('City', related_name="business")
hood = models.ForeignKey('Hood', null=True, blank=True, related_name="business")
....

还有 HTML 模板?

谢谢!

最佳答案

查看关于聚合的文档: https://docs.djangoproject.com/en/1.6/topics/db/aggregation/

您应该能够编写一个 View ,该 View 返回一个查询集,其计数与此类似:

from django.db.models import Count
Hood.objects.filter(business__city_id=8).annotate(bus_count=Count('business__id'))

至于 HTML,这完全取决于您。不过,如果您提供该查询集,则可以使用 {{ object.bus_count }} 获取计数。

关于python - 带有 JOIN 和 GROUP BY SQL 查询的 Django COUNT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22414042/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com