Question

I'm using Django's built in form.ModelForm and formset_factory to provide a set of forms for user input. Some of the fields on the form are select boxes and the data in those boxes are comprised of several fields so I expect several DB hits per each selection. However, when I add extra forms (e.g. by using the "extra" parameter) for each extra form it hits the DB again. For example, if there are 4 DB hits to make 1 selection, and there are 10 selections we expect 40 queries. But if I add 5 "extra" inlines, all of a sudden there are 4 * 10 * 5 for 200 queries. Doesn't formset_factory realize the selection box is the same for all of the inlines? Why so many database hits? Is there a better way to do this? In my opinion the selections should be generated once, and used for each selection box (i.e., 40 queries for this particular example).

Was it helpful?

Solution

I would definitely agree that the form sets should be smart enough to not query it so many times. I have run into this many times. I ended up doing something this:

class TestFormset(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        super(TestFormset,self).__init__(*args, **kwargs)

        awesome_models = AwesomeModel.objects.all()

        for form in self.forms:
            form.fields['awesome_model'].choices = [('', '--------')] + [(x.pk, x.name) for x in awesome_models]

This basically just runs one query, then manually setting the choices the particular field for each form in the form set.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top