1

对于此代码:

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 对象上运行后续过滤器的正确方法是什么,而不是单独使用数据库?

4

1 回答 1

2

为了不对每个名字进行数据库查询,唯一的方法是在 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) 中做一些事情。我只是在 a 中添加人员,dict但这一步不是必需的。

于 2012-10-14T02:18:57.703 回答