简体   繁体   English

django:针对get_context_data中的get_queryset结果进行计算

[英]django: calculation against result of get_queryset in get_context_data

While using django's generic ListView, I want to include some extra context data which is calculated against the result of get_queryset, for example: 在使用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

will this cause any (performance or other) issue if I do it like above? 如果我像上面那样这样做会导致任何(性能或其他)问题吗? it seems a little weird, is there any better approach for doing this? 似乎有点不可思议,是否有更好的方法可以做到这一点?

beside of that, I'm calling the get_queryset without any args and kwargs in get_context_data, how can I ensure I'm getting the exactly the same result with what it called automatically? 除此之外,我要在get_context_data中调用没有任何args和kwargs的get_queryset,如何确保获得与自动调用的结果完全相同的结果?

It would be perfect if there is something storing the result of get_queryset before entering get_context_data, so I can just retrieve the result, does it exist? 如果在输入get_context_data之前先存储get_queryset的结果,那将是完美的,所以我可以检索结果,它存在吗?

除了您应该使用queryset .count()方法而不是对其调用len()之外,这还不错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM