2015-10-29 32 views
1
class Author(models.Model): 
    name = models.CharField() 

class Article(models.Model): 
    author = models.ForeignKey(Author) 

外鍵模型假設我需要一個模板許多Articles是如何從一個確定的作家顯現。這是觀點:正確的方法來計算在Django的模板

def myview(request): 
    context = { 
     'authors': Author.objects.all() 
    } 

只是在做{{ author.Articles||length }}將需要我編輯作者模型。如果這是正確的方式(顯然不是),我應該在models.py級別還是在myview視圖中執行此操作?

我相信在models.py編輯模型會導致一個非常糟糕的代碼設計。

這樣做在myview需要我做這樣的事情:

authors = [] 
for author in authors: 
    count = Article.objects.filter(author__exact=author).count() 
    authors.append(author, count) 
    horrendously_bad_code_design_context = { 
     'authors': authors, 
    } 

什麼是這樣做的正確方法?我相信這兩種實現都非常糟糕,而且「哈克」。

+1

您可以在視圖中執行'author.article_set.count()'。 – Ivan

+0

我不知道這個「_set」屬性(我還是Django的新手)。如果你確定這個工作正常,請把它作爲甜點的回答:) – Saturnix

+2

這是非常基本的,所以我不會發佈一個答案 - 它只是背誦文檔。請參閱[相關對象](https://docs.djangoproject.com/en/1.8/ref/models/relations/)。 – Ivan

回答

1

如果您已經有檢索到的作者,並且想要獲得文章數量,那麼使用related manager'scount方法(author.article_set.count())可能沒問題。另一方面,如果您爲了獲取計數而遍歷(可能是滯後的)Author queryset,它將執行很多查詢(一個檢索所有作者,一個檢索所有作者以獲得計數)。這可以通過一個annotated queryset,這將導致只有一個查詢很容易地更換:

from django.db.models import Count 

Author.objects.annotate(article_count=Count('articles')) 
後來在你

在你的模板,你可以只使用{{ author.article_count }}