#31295: Avoid Select widget triggering additional query in ModelChoiceIterator.
-------------------------------------+-------------------------------------
     Reporter:  Aurélien Pardon      |                    Owner:  nobody
         Type:                       |                   Status:  closed
  Cleanup/optimization               |
    Component:  Forms                |                  Version:  2.2
     Severity:  Normal               |               Resolution:  needsinfo
     Keywords:  Model                |             Triage Stage:  Accepted
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------
Changes (by Carlton Gibson):

 * stage:  Unreviewed => Accepted


Comment:

 Hi Aurélien,

 > Maybe there's a way of performing that Select.use_required_attribute()
 check without fetching the first item...?

 It strikes me that we might be able to do this. This patch passes the
 existing tests:

 {{{
 diff --git a/django/forms/widgets.py b/django/forms/widgets.py
 index 40ac1d3162..5bc040065a 100644
 --- a/django/forms/widgets.py
 +++ b/django/forms/widgets.py
 @@ -696,7 +696,16 @@ class Select(ChoiceWidget):
          if self.allow_multiple_selected:
              return use_required_attribute

 -        first_choice = next(iter(self.choices), None)
 +        iterator = iter(self.choices)
 +        # Avoid an extra query if we have a ModelChoiceIterator.
 +        try:
 +            empty_label = iterator.field.empty_label
 +        except AttributeError:
 +            pass
 +        else:
 +            if empty_label is not None:
 +                return use_required_attribute
 +        first_choice = next(iterator, None)
          return use_required_attribute and first_choice is not None and
 self._choice_has_empty_value(first_choice)
 }}}

 So with a further test asserting number of queries, a think about any edge
 cases, and a tidy up, I think we can evaluate a patch on that basis.

 Thanks for your input!

-- 
Ticket URL: <https://code.djangoproject.com/ticket/31295#comment:10>
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/065.714af7ae2fed8946e9efb04c18a227bf%40djangoproject.com.

Reply via email to