空列表上的Django Queryset过滤器 [英] Django Queryset Filter on an empty list
问题描述
我正在构建动态过滤器,该过滤器通过GET传递给查询集过滤器:
I'm building dynamic filters which I pass by GET to a queryset filter:
for k, v in request.GET.iteritems():
kwargs[str(k)] = str(v)
students = models.Student.objects.filter( **kwargs )
,它几乎可以解决我提出的所有查询.但是,我有一个具有许多关系的相关模型Group.因此,一个学生可以成为许多小组的成员.我可以使用以下过滤条件来过滤属于给定组的学生:
'groups__in='+str(group.id)
and it's working for almost all the queries I'm throwing at it. However, I have a related model with a manytomany relationship, Group. So a student can be a member of many groups. I'm able to filter students who belong to a given group using the following:
'groups__in='+str(group.id)
例如-//example.com/students/?groups__in=1
e.g. - //example.com/students/?groups__in=1
但是我不知道该如何过滤不属于任何组的学生.我已经尝试了以下方法,但没有成功:
But I can't figure out how to filter for students who don't belong to any group. I've tried the following without success:
groups__in=None # students == []
groups__exact=None # students == []
groups__iexact=None # FAIL not that I really expected this to work
groups__isnull=True # students == []
最后一个版本是我希望能够实际工作的版本.我敢肯定,可以通过将顶部代码修改为类似的东西来使它工作
The last version was what I was hoping to have actually work. I'm sure I could get this to work by modifying the top code to something like
if request.GET['something']:
students = models.Student.objects.exclude(groups__isnull=False)
else:
students = models.Student.objects.filter( **kwargs )
所以我想问题变成了,我该如何创建
So I guess the question becomes, how can i create
students = models.Student.objects.exclude(groups__isnull=False)
使用.filter()吗?
using .filter()?
推荐答案
也许我不明白这个问题.但我看到了:
Maybe I don't understand the question. But I see:
list(MyMod.objects.exclude(foo__isnull=False)
) == list(MyMod.objects.filter(foo__isnull=True))
这篇关于空列表上的Django Queryset过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!