Django处理MultipleChoiceField数据需要很长时间
问题描述:
我是Django的新成员,并且遇到MultipleChoiceField的POST请求时间过长的问题。它有人名单,我想显示地址列表,这些人住在那里的时间与他们住在一起,但我的解决方案太慢了。因此,如果我选择3 +人加载时间变得非常大(4-5秒),但数据库查询只需要0.5-0.7秒(如Django的调试工具栏说),这就是为什么我没有创建任何索引尚未(我会创建它们)。我认为长页面加载的问题是关于我错误的观点工作。同样在django-debug-toolbar的'Timer'面板中,大部分时间都需要“Request”部分。Django处理MultipleChoiceField数据需要很长时间
简化我的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
forms.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:'
)
views.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})
我所要求的任何建议,以优化我的应用程序,谢谢!
答
首先,您可以使用sql进行排序,然后对于套管,您可以使用css来代替。
((person['id'], person['name'].lower()) for person in sorted(
Person.objects.all().values('id', 'name'), key=itemgetter('name'))),
BECOMES
forms.MultipleChoiceField(choices=Person.objects.order_by('name').values('id', 'name'))
With CSS:
.lowercase {
text-transform: lowercase;
}
对于形式保存的部分,你可以发帖者和众议院的模式?
+0
虽然我没有索引,db-sort只是添加了一点时间。我已经发布了我的models.py。你的意思是发布forms.py? – vadimb
什么是组合代码? – ahmed
@ahmed thats从itertools模块的功能。 https://docs.python.org/2/library/itertools.html#itertools.combinations – vadimb