【问题标题】:Django COUNT with JOIN and GROUP BY SQL query带有 JOIN 和 GROUP BY SQL 查询的 Django COUNT
【发布时间】:2014-04-20 06:40:22
【问题描述】:

该 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 模板呢?

谢谢!

【问题讨论】:

  • 不要使用switch作为变量名
  • 正确的视图和 HTML 是什么意思?您可以决定如何处理这些数据...

标签: python mysql sql django


【解决方案1】:

查看有关聚合的文档: 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 }} 获得计数。

【讨论】:

  • 谢谢!正是我想要的!顺便说一句,我已经编写 SQL 查询 15 年了,但是这个 Django SQL 的东西与我习惯的不同。 :)
猜你喜欢
  • 2021-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-09
  • 1970-01-01
  • 2016-05-01
  • 2021-12-19
  • 2010-10-30
相关资源
最近更新 更多