我是 Django 的新手,遇到了 MultipleChoiceField 的高 POST 请求时间问题。它有人员列表,我想显示地址列表,这些人住在那里的时间和他们住在那里的时间,但我的解决方案太慢了。
因此,如果我选择 3 个人以上的加载时间变得非常大(4-5 秒),但 db 查询只需要 0.5-0.7 秒(如 django-debug-toolbar 所说),这就是为什么我还没有创建任何索引(我将创建它们)。我认为长页面加载的问题与我的错误视图工作有关。同样在 django-debug-toolbar 的“计时器”面板中,大部分时间都需要“请求”部分。
我的models.py的简化版本:
class Person(models.Model):
name = models.CharField(max_length=300)
class House(models.Model):
name = models.CharField(max_length=300)
persons = DictField() # stores {person_id: time_lived} - persons, who lived here
表格.py:
class PersonListForm(forms.Form):
persons= forms.MultipleChoiceField(choices=
((person['id'], person['name'].lower()) for person in sorted(
Person.objects.all().values('id', 'name'), key=itemgetter('name'))),
label='Choice person list:'
)
视图.py:
class ChoicePersonView(FormView):
template_name = 'guess_houses.html'
form_class = PersonListForm
def get(self, request, *args, **kwargs):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
persons_id = form.cleaned_data['persons']
houses = [] # list of houses i want to display
t1 = time()
comb = [] # I need all houses, where lived any of these persons
for r in range(1, len(persons_id )+1):
comb += [i for i in combinations(persons_id ,r)]
for id_person_dict in House.objects.all().values('id', 'persons', 'name'):
for c in comb:
if set(c).issubset(set(id_person_dict['persons'])):
if id_person_dict not in houses:
houses.append(id_person_dict)
return render(request, self.template_name, {'form': form, 'houses': houses, 't': time() - t1})
我正在寻求任何建议来优化我的应用程序,谢谢!