【问题标题】:counting/filtering database-entries over multiple foreign key-relations在多个外键关系上计数/过滤数据库条目
【发布时间】:2013-05-22 07:48:11
【问题描述】:

这些是我的数据库模型:

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'))

提取这些信息的正确方法是什么? 特别是如果我想添加更多信息,例如:类别中的提要数量和 一个 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

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

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    您必须标记信息。如果您使用下面的查询,您应该可以将category.article_count 用于查询集中的项目。

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

    【讨论】:

    • 嗨 relekang,感谢您的供应。但是即使一个是空的(相关提要没有文章),我如何显示所有类别?
    • 它应该可以工作。 article_count 将为零,但类别在查询集中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多