0
過濾數據庫條目這是我的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)
...
每一篇文章屬於一個頻道(源)和各飼料中的一個類別。
現在,我想創建一個視圖來顯示全部類別與一些元信息, 例如,類別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
我敢肯定有一個更快,更好的方式來獲得這些信息,但至少我現在可以使用它:/
hi relekang,謝謝你的供應。但是我怎麼能顯示所有類別,即使一個是空的(相關的飼料沒有文章)? – marv
當然,我的意思是:感謝您的**回覆**;) – marv
它應該工作。 article_count將爲零,但該類別位於查詢集中。 – relekang