在使用 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 中调用 get_queryset 时没有任何参数和 kwargs,如何确保我得到与其自动调用的结果完全相同的结果?
如果在输入 get_context_data 之前有东西存储 get_queryset 的结果就完美了,这样我就可以检索结果,它存在吗?
最佳答案
这很好,除了您应该使用 queryset .count()
方法而不是调用 len()
的事实。
关于python - django:根据 get_context_data 中的 get_queryset 结果进行计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22639902/