Django filter on multiple array list values

I have to do a filter according to 3 fields: Doctor, Client and Branch. Each one of them is an array of ids, so I want to filter by these ids.

My django view code:

my_dict = {
    'BranchId': [0,1,2,4],
    'DoctorId': [2,4,5],
    'ClientId': [2,3,5],
}

Branches = my_dict['BranchId']
Doctors = my_dict['DoctorId']
Clients = my_dict['ClientId']

query = Event.objects.all().filter(
    e_d__in=Doctors,
    e_b__in=Branches,
    e_c__in=Clients)
print(query) 

1 answer

  • answered 2018-10-12 10:11 Ralf

    I don't fully understand what your question is exactly, but I'll try to explain the concept of the query.

    If you use the field lookup __in in a queryset, the value of your field has to be one of the values present in the list you provide.

    Here is a reduced version of your code (it has the same functionality, but with more explicit names and less lines of code).

    my_dict = {
        'branch_id_list': [0, 1, 2, 4],
        'doctor_id_list': [2, 4, 5],
        'client_id_list': [2, 3, 5],
    }
    query = Event.objects.filter(
        e_d__in=my_dict['branch_id_list'],
        e_b__in=my_dict['doctor_id_list'],
        e_c__in=my_dict['client_id_list'])
    print(query)
    

    This code expects that your model Event has the 3 fields e_a, e_b and e_c; each of them has to be an IntegerField (or something similar that has an int as its base type).

    The query will return all Event instances where the 3 conditions are met; that is, each of the 3 fields needs to have a value that is in there respective lists.

    Does that answer your question?