在多个外键关系上计算/筛选数据库条目

2024-04-25 06:25:53 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我的数据库模型:

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

每一篇文章都属于一个提要(源),每个提要都属于一个类别。你知道吗

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

我试过这样的方法,但没有成功:

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

提取这些信息的正确方法是什么? 特别是如果我想添加更多的信息,比如:分类和 一个查询集中的首选项目数(如果可能的话)。。。你知道吗

有什么想法吗? 谢谢。你知道吗

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

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

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


Tags: 方法info信息readiftitlemodelsfeed
1条回答
网友
1楼 · 发布于 2024-04-25 06:25:53

你必须给信息贴上标签。如果使用下面的查询,您应该能够对queryset中的项使用category.article_count。你知道吗

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

相关问题 更多 >