Django get_queryset return custom variables

元气小坏坏 提交于 2020-06-29 06:41:06

问题


Using users as an example I am trying to show how many users there are. get_context_data works totally fine but get_queryset does not. I know that it's not set up properly but I've been playing around with it for quite some days and something is just not clicking..

The main goal is to use the Dajngo-Filter form and then be able to get the updated number of user count. I've only found endless documentation on how to show the "list" of users. Which I have done but no documentation on how to show custom variables. I have many statistics & charts I'd like to calculate based on the filters applied.

class UserFilterView(LoginRequiredMixin, FilterView):
    template_name = 'community/user_list.html'
    model =  User
    filterset_class = UserFilter

    def get_queryset(self):
        user_count = User.objects.all().count()

    def get_context_data(self, *args, **kwargs):
        context = super(UserFilterView, self).get_context_data(*args, **kwargs)
        context['user_count'] = User.objects.all().count()
        return context

回答1:


context['user_count'] = User.objects.all().count()

is set to always count all users. So, of course, it's going to always do what it's programmed it to do.

Instead, I should use .count from the filtered queryset.

view.py

class UserFilterView(LoginRequiredMixin, FilterView):
    template_name = 'community/user_list.html'
    model =  User
    filterset_class = UserFilter

    def get_context_data(self, *args, **kwargs):
        context = super(UserFilterView, self).get_context_data(*args, **kwargs)
        context['qs'] = User.objects.all()
        return context

template:

User Count: {{ filter.qs.count }}


来源:https://stackoverflow.com/questions/61951419/django-get-queryset-return-custom-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!