views:

106

answers:

3

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?

+1  A: 

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

Daniel Roseman
It does not, Django still queries for each of the forms in the formset.
Martin
A: 

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

dragoon
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
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
+1  A: 

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

Matthew Schinckel
I'll look into it, thanks!
Martin