对于此SQL查询,正确的Django视图和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/
您应该能够编写一个视图,该视图返回一个查询集,其计数与此类似:
from django.db.models import Count
Hood.objects.filter(business__city_id=8).annotate(bus_count=Count('business__id'))
至于HTML,这完全取决于您。不过,如果您提供该查询集,则可以使用进行计数{{ object.bus_count }}
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句