计算/过滤多个外键关系上的数据库条目

时间:2013-05-27 12:39:43

标签: python django django-models

这些是我的DB模型:

class Category(models.Model):
    name = models.CharField(max_length = 20, unique = True)
    ...

class Feed(models.Model):
    title = models.CharField(max_length = 100)
    category = models.ForeignKey(Category)
    ...

class Article(models.Model):
    title = models.CharField(max_length = 100)
    read = models.BooleanField(default = False)
    feed = models.ForeignKey(Feed)
    ...

每篇文章都属于一个Feed(来源),每个Feed都属于一个类别。

现在,我想创建一个视图,用一些元信息显示所有类别, 例如x类中有多少未读文章。

我尝试过这样的事情,但没有任何效果:

categories = Category.objects.filter(feed__article__read=False)\
                             .annotate(Count('feed__article'))

提取这些信息的正确方法是什么? 特别是如果我想添加更多信息,例如:类别和数量的Feed 一个QuerySet中受欢迎的文章数量(如果可能)......

有什么想法吗? 感谢。

编辑:由于我不知道如何“解决”这个问题,我写了一个丑陋的解决方法:

result = categories.values_list('name', 
                                'feed__title', 
                                'feed__article__title', 
                                'feed__article__read')

for i in range(0, len(result)):

    #if pointer changed to a new category
    #dump current dict to list and clear dict for the new values
    if last != result[i][0]:
        category_list.append(category_info.copy())
        category_info.clear()
        last = result[i][0]         

    if some values None:
         insert values        
    elif some other values None:
         insert values

    else:

        category_info['name'] = result[i][0]
        category_info['feed_count'] = category_info.get('feed_count', 0) + 1
        category_info['all_article_count'] = category_info.get('all_article_count', 0) + 1
        #if a article has not been read yet
        if result[i][3] == False:
            category_info['unread_article_count'] = category_info.get('unread_article_count', 0) + 1

    #if this category is the last in the result-list
    if i+1 == len(result):
        category_list.append(category_info.copy())

    i += 1

我很确定有更快更好的方法来获取这些信息,但至少我现在可以使用它:/

1 个答案:

答案 0 :(得分:0)

您必须标记信息。如果您使用以下查询,则应该能够使用category.article_count作为查询集中的项目。

categories = Category.objects.filter(feed__article__read=False)\
                         .annotate(article_count=Count('feed__article'))