M.Izzat
M.Izzat

Reputation: 1166

django form queryset multiple same field filter

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) 

Upvotes: 3

Views: 1210

Answers (1)

Alasdair
Alasdair

Reputation: 308869

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])

Upvotes: 4

Related Questions