Django get_queryset返回自定义变量 [英] Django get_queryset return custom variables
问题描述
以用户为例,我试图显示有多少用户。 get_context_data
可以很好地工作,但 get_queryset
不能。我知道它的设置不正确,但是我已经玩了很多天了,而且有些东西没有点击。.
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..
主要目标是使用 Dajngo-Filter 表单,然后能够获取更新的用户数。我只找到了无数有关如何显示用户列表的文档。我已完成但没有有关如何显示自定义变量的文档。我有很多统计数据我想根据所应用的过滤器来计算图表。
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
推荐答案
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.
相反,我应该从过滤后的查询集中使用.count。
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
模板:
User Count: {{ filter.qs.count }}
这篇关于Django get_queryset返回自定义变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!