5

I need to display multiple forms (up to 10) of a model on a page. This is the code I use for to accomplish this.

TheFormSet = formset_factory(SomeForm, extra=10)
...
formset = TheFormSet(prefix='party')

return render_to_response('template.html', {
        'formset' : formset,
})

The problem is, that it seems to me that Django queries the database for each of the forms in the formset, even though the data displayed in them is the same.

Is this the way Formsets work or am I doing something wrong? Is there a way around it inside django or would I have to use JavaScript for a workaround?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Martin
  • 61
  • 2
  • You might check the solution from this question http://stackoverflow.com/questions/15203207/prevent-django-from-querying-for-foreignkey-options-for-every-form-in-modelforms – Tomasz Zieliński Mar 15 '13 at 22:35

3 Answers3

1

What happens if you use modelformset_factory instead of formset_factory? Does that help?

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
1

If the queries are all identical, it may be worth looking at johnny-cache, and see if that will improve performance.

Matthew Schinckel
  • 35,041
  • 6
  • 86
  • 121
0

Are you sure that django queries database? Try to use Django Debug Toolbar to see what queries django actually makes.

dragoon
  • 5,601
  • 5
  • 37
  • 55
  • Thanks for the suggestion. I installed the toolbar and it confirms the huge number of queries. The model has many foreign key fields, so to display on of the forms a total of 8 queries are performd, which is already a lot, so when I want to display 10 a total of 80 queries are made! – Martin May 17 '10 at 08:34
  • Are you sure that queries to database are performed when you creating a formset? Or may be queries are made when you populate formset with data from database? Anyway, try to use [select_related][1] on your querysets to reduce the number of actual queries [1]: http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4 – dragoon May 17 '10 at 19:27