vadimb
vadimb

Reputation: 462

Django processing MultipleChoiceField data takes too long

I'm new in Django and got problems with high POST-request time of MultipleChoiceField. It has list of persons, and i want to display list of addresses, where these persons lived with time they lived there, but my solution is too slow.

So if i select 3+ persons load-time is becoming very big (4-5 seconds), but db queries takes only 0.5-0.7 seconds (as django-debug-toolbar says), thats why I didnt created any indexes yet (I will create them). I think the problem of long page load is about my wrong view work. Also in 'Timer' panel of django-debug-toolbar most of the time takes "Request" section.

simplified version of my 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})

I'm asking for any advices to optimize my app, thank you!

Upvotes: 0

Views: 473

Answers (1)

Du D.
Du D.

Reputation: 5300

First you can sort using sql, and then for the casing you can do it with css instead.

((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;
}

For the form saving part can you post the model of Person and House?

Upvotes: 0

Related Questions