0

我是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}) 

我所要求的任何建議,以優化我的應用程序,謝謝!

+0

什麼是組合代碼? – ahmed

+0

@ahmed thats從itertools模塊的功能。 https://docs.python.org/2/library/itertools.html#itertools.combinations – vadimb

回答

0

首先,您可以使用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