[英]django form queryset multiple same field filter
I'm trying to filter my user field queryset based on 3 department id. 我正在尝试基于3个部门ID来过滤我的用户字段queryset。 I'm able to filter a single department but when I try to filter multiple times it's not working.
我可以过滤单个部门,但是当我尝试多次过滤时,它不起作用。 Can anyone help me with this?
谁能帮我这个? My code is below:
我的代码如下:
form.py form.py
class EditProjectForm(forms.ModelForm):
prefix = 'edit_form'
class Meta:
model = Model_A
fields = '__all__'
def __init__(self, user, *args, **kwargs):
super(EditProjectForm, self).__init__(*args, **kwargs)
self.fields['user'].queryset = Employee.objects.filter(department__id=18).filter(department__id=19).filter(department__id=20)
Your current query is trying to find employees which have department id 18 and 19 and 20. If department
is a foreign key, that is not possible. 您当前的查询试图找到具有部门ID 18,19 和 20名员工。如果
department
是一个外键,这是不可能的。
You can use Q()
objects to find employees which have department id 18 or 19 or 20. 您可以使用
Q()
对象查找部门ID为18 或 19 或 20的员工。
Employee.objects.filter(Q(department=18)|Q(department=19)|Q(department=20))
However in your case, the simplest solution is to use __in
to return employees where the department id is any one of 18, 19 or 20. 但是,在您的情况下,最简单的解决方案是使用
__in
返回部门ID为18、19或20中任何一个的雇员。
Employee.objects.filter(department__in=[18, 19, 20])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.