Django查询以检索具有该查询集的后续查询的初始查询集

时间:2012-10-14 00:33:12

标签: django django-queryset

对于此代码:

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. 

我对django查询集的理解是,在您“需要”数据之前,实际上不会执行查询,从而允许优化链式查询集。但是,如果我没有弄错的话,这似乎对我不利;将要执行的第一个查询基本上等同于:

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

需要为每个名字查询数据库。如果是这种情况,那么让Django实际检索people_pool然后在检索到的python对象上运行后续过滤器,让数据库保持单独的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

为了不对每个名字进行db查询,唯一的方法是在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

如果需要,您也可以在第一个循环(for person in people_pool)中执行某些操作。我只是在dict中添加人员,但这一步不是必需的。