#32244: ORM inefficiency: ModelFormSet executes a single-object SELECT query per
formset instance when saving/validating
-------------------------------------+-------------------------------------
     Reporter:  Lushen Wu            |                    Owner:  nobody
         Type:                       |                   Status:  new
  Cleanup/optimization               |
    Component:  Database layer       |                  Version:  3.1
  (models, ORM)                      |
     Severity:  Normal               |               Resolution:
     Keywords:  formsets             |             Triage Stage:
                                     |  Unreviewed
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------

Comment (by Lushen Wu):

 I figured out a very hacky workaround that preserves the formset
 functionality we need. Basically in {{{BookForm}}} you can override
 {{{ModelForm._clean_fields()}}}

 {{{
 def _clean_fields(self):
         # remove 'id' field so it's not cleaned
         # (this is the ModelChoiceField that's generating an extra SELECT
 query per Book object in the formset during clean)
         id_field = self.fields.pop('id')

         # run normal cleaning, with the form now unaware of its own 'id'
 field
         super(BookForm, self)._clean_fields()

         # add 'id' field back and insert it into clean_data
         id_value = id_field.widget.value_from_datadict(self.data,
 self.files, self.add_prefix('id'))
         self.cleaned_data['id'] = id_value

         # add the 'id' field back into the form
         self.fields['id'] = id_field
 }}}

-- 
Ticket URL: <https://code.djangoproject.com/ticket/32244#comment:6>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/066.009eeb1fa16677f3650275b321009be7%40djangoproject.com.

Reply via email to