﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
26800	Model FormSet & Prefetch ordered	Adrien mille	nobody	"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.
"	Uncategorized	new	Uncategorized	1.9	Normal		formset preferch order_by ordered model		Unreviewed	0	0	0	0	0	0
