Django加入。选择数据+选择计数

时间:2014-11-23 19:10:00

标签: python django join

两种型号:

class KeywordCategory(models.Model):
    class Meta():
        db_table = 'keywords_category'
    category_name = models.CharField(max_length = 100)
...
class Keyword(models.Model):
    class Meta():
        db_table = 'keywords'
    keyword_category = models.ForeignKey(KeywordCategory)
    keyword_text     = models.CharField(max_length = 100)

我需要获取所有类别和条目数。

SQL语法:

SELECT keywords_category.*, COUNT(keywords.id) as count_keywords
FROM keywords_category
LEFT JOIN keywords ON keywords_category.id=keywords.keyword_category_id
GROUP by keywords_category.id

3 个答案:

答案 0 :(得分:4)

这将返回字典,密钥将为keyword_categorytotal

from django.db.models import Count

kw_counts = Keyword.objects.all().values('keyword_category').annotate(
    total=Count('keyword_category')
)

答案 1 :(得分:0)

获取所有类别:

categories = KeywordCategory.objects.all()

计算其中的条目:

for category in categories:
    category.keyword_set.count()

答案 2 :(得分:0)

keywords = KeywordCategory.objects.all()

print [(k, k.keyword_set.count()) for k in keywords]