Python 在多个外键关系上计算/筛选数据库条目
以下是我的数据库模型:Python 在多个外键关系上计算/筛选数据库条目,python,django,django-models,Python,Django,Django Models,以下是我的数据库模型: 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(
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
我确信有一种更快更好的方法来获取这些信息,但至少目前我可以使用它:/您必须标记这些信息。如果使用下面的查询,您应该能够对查询集中的项目使用
category.article\u count
categories = Category.objects.filter(feed__article__read=False)\
.annotate(article_count=Count('feed__article'))
嗨,瑞康,谢谢你的供应。但是,即使其中一个类别是空的(相关提要没有文章),我如何显示所有类别呢?应该可以。文章计数将为零,但类别在queryset中。