#26800: Model FormSet & Prefetch ordered
-------------------------+-------------------------------------------------
     Reporter:           |      Owner:  nobody
  amille44420            |
         Type:           |     Status:  new
  Uncategorized          |
    Component:           |    Version:  1.9
  Uncategorized          |   Keywords:  formset preferch order_by ordered
     Severity:  Normal   |  model
 Triage Stage:           |  Has patch:  0
  Unreviewed             |
Easy pickings:  0        |      UI/UX:  0
-------------------------+-------------------------------------------------
 I happened to meet some unexpected behavior while mixing together the
 Model FormSet with a Queryset on which I had prefetch.

 My setup is the following one ;

 {{{
 #!python
 prefetch = Prefetch('childs', Child.objects.order_by('order')),
 queryset = Parent.objects.prefetch_related(prefetch)
 parent = queryset.get(pk=42)
 formset = ChildFormSet(queryset=parent.childs.all())
 }}}

 Everything works without warning or error, however the formset does not
 respect the queryset I provide. I tried to understand a bit more about the
 reasons behind it and I finally see the folloxing lines in
 BaseModelFormSet.get_queryset() ;

 {{{
 "!python
 # If the queryset isn't already ordered we need to add an
 # artificial ordering here to make sure that all formsets
 # constructed from this queryset have the same form order.
 if not qs.ordered:
      qs = qs.order_by(self.model._meta.pk.name)
 }}}

 So I went to read my queryset object and I saw that the property ordered
 is to False while the results are correctly ordered (the property
 _prefetch_done is True on my queryset object). So my thinking is that the
 queryset resulting of parent.object.all() is my prefetch (as expected) but
 not ordered as my FormSet expects. So it does order it by the primary key
 for the model and breaks my prefetch.

 I checked twice on the documentation and source code but I didn't see any
 warning about putting together prefetch & formset, especially on ordered
 queryset.

--
Ticket URL: <https://code.djangoproject.com/ticket/26800>
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 post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/054.557f8b651cd2f82c9539d8785a26863a%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to