[英]django: calculation against result of get_queryset in get_context_data
在使用django的通用ListView時,我想包括一些額外的上下文數據,這些數據是根據get_queryset的結果計算的,例如:
class BookListView(ListView):
model = Book
context_object_name = 'book_list'
template_name = 'book_list.html'
def get_queryset(self, *args, **kwargs):
qset = super(BookListView, self).get_queryset(*args, **kwargs)
return qset.filter(owner=self.request.user)
def get_context_data(self, **kwargs):
context = super(BookListView, self).get_context_data(**kwargs)
// just take this as an example, here the extra context data may be some
// complex result which is calculated against the result of get_queryset
context['2012_books_nr'] = self.get_queryset().filter(publish_year='2012').count()
return context
如果我像上面那樣這樣做會導致任何(性能或其他)問題嗎? 似乎有點不可思議,是否有更好的方法可以做到這一點?
除此之外,我要在get_context_data中調用沒有任何args和kwargs的get_queryset,如何確保獲得與自動調用的結果完全相同的結果?
如果在輸入get_context_data之前先存儲get_queryset的結果,那將是完美的,所以我可以檢索結果,它存在嗎?
除了您應該使用queryset .count()
方法而不是對其調用len()
之外,這還不錯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.