Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django form queryset multiple same field filter

Tags:

python

django

I'm trying to filter my user field queryset based on 3 department id. 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

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) 
like image 796
M.Izzat Avatar asked Jun 23 '26 23:06

M.Izzat


1 Answers

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.

You can use Q() objects to find employees which have department id 18 or 19 or 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.

Employee.objects.filter(department__in=[18, 19, 20])
like image 133
Alasdair Avatar answered Jun 25 '26 14:06

Alasdair