B Robster
B Robster

Reputation: 42043

Django query to retrieve an initial queryset with subsequent queries on that queryset

For this code:

people_pool = People.objects.filter(last_name__in = last_names)
for first_name in first_names:
    for person in people_pool.filter(first_name = first_name):
       # do something with each person. 

My understanding from django querysets is that a query won't actually be executed until you "need" the data, thus allowing for optimization of chained querysets. However, if I'm not mistaken, that would seems to work against me here; the first query that will be executed is essentially going to be the equivalent of:

People.objects.filter(last_name__in = last_names, first_name = first_name) # for the first first_name in first_names

And the database will need to be queried for every single first name. If this is the case, what is the proper way to get Django to actually retrieve the people_pool and then run subsequent filters on the retrieved python objects, leaving the DB alone?

Upvotes: 1

Views: 117

Answers (1)

miki725
miki725

Reputation: 27861

In order not to do a db query for each first name, the only way is to do the actual filtering in Python:

people_pool = People.objects.filter(last_name__in = last_names)
people = {}

for person in people_pool:
    first_name = person.first_name
    if first_name in first_names:
        if not first_name in people:
            people[first_name] = []
        people[first_name].append(person)

for first_name, people_first_name in people.items():
    for person in people_first_name:
        # do something with each person

If you want, you can also do something in the first loop (for person in people_pool). I just add people in a dict but that step is not necessary.

Upvotes: 2

Related Questions