2014-11-23 60 views
0

有兩種型號:Django JOIN。選擇數據+ SELECT COUNT

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 

回答

4

這將返回一個字典和鍵將是keyword_categorytotal

from django.db.models import Count 

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

@ qor1x'.objects.values('keyword_category__category_name')' – madzohan 2014-11-24 11:17:53

0

獲取所有類別:

categories = KeywordCategory.objects.all() 

計數的條目在其中:

for category in categories: 
    category.keyword_set.count() 
0
keywords = KeywordCategory.objects.all() 

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