0

我有一个简单的项目,现在几乎什么都不做 - 有带有一些 Person-values 的 MultipleChoiceField,当用户选择一些值并单击“提交”按钮时 - 我正在寻找选定的人居住的房屋。

我的数据库中有大约 1.5k 人和 20k 房屋。如果我从列表中选择 3+ 人(在这种情况下,“房屋”列表中大约有 5-6k 个值),处理时间需要很长时间(我的“t”变量约为 5-7 秒)。

正如 django-debug-toolbar 所说,数据库查询只需要 0.7 秒,大约 95% 的时间是“计时器”面板的“请求”部分。所以问题是 - 我做错了什么?我认为使用 render_to_response 的方式是错误的。你能推荐我一些东西来优化我的代码吗?我是 Django 的新手,谢谢。

在我的“guess_houses.html”中,我只显示带有他们字段的房屋列表。

这是我的views.py:

class HouseView(FormView):
    template_name = 'guess_houses.html'
    form_class = PersonListForm # that's my MultipleChoiceField with persons in it

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            persons_id = form.cleaned_data['persons']
            houses= []
            t1 = time()
            for id_person_dict in House.objects.all().values('id', 'persons', 'address'):
                # if persons_id and persons who lived in house got intersection element(s)
                if set(persons_id) & set(id_person_dict['persons']):
                    if id_person_dict not in houses:
                        houses.append(id_person_dict)
        return render_to_response(self.template_name, {'form': form, 'houses': houses, 't': time()-t1})
4

0 回答 0