问题
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