> That's works really thank you for your time, learned a very good thing
> today, 1 week im on this X) . Already look a little to Prefetch() function
> but haven't understand how to use it in my case^^
>
Don't feel that bad. Prefetch() stumped me for a long time until I saw a
post about it on this list a year or so back, and the Django dev team added
examples to the documentation which clarified even more.
>
> I have replaced my {% with currscat=categ.getscateg %} by {% with
> currscat=categ.souscategorie_set.all %} like in your example, that's work
> "_set.all" return me only "visible" child without more request but i don't
> understand how that's work, it is supposed to return me all objects, it
> don't include a filter, Prefetch() function do this?
>
The filter to only retrieve the 'visible' related objects is built into the
Prefetch() objects as part of the queryset:
pf_souscategorie = Prefetch('souscategorie_set',
SousCategorie.objects.filter(visible=True)) # prefetch only visible
SousCategorie's
Here, the PF object is configured to use the query
SousCategorie.objects.filter(visible=True) when it pre-fetches all of the
related SousCategorie objects.
When you access the set that was pre-fetched (using the PF object), the
.all() will only gather the rows that were pre-fetched and cached in the
queryset, and not execute a typical .all() query against the DB (which is
the point of pre-fetching, not to run queries later). Since we limited the
original query with a PF object, any subsequent
categ.souscategorie_set.all() calls use the pre-fetched rows, and hence are
filtered.
If you wanted to see all of the objects and have the
souscategorie_set.all() work as it does typically (fetching all of the
related rows instead of just the visible ones), you can do this instead:
# Note that we do not need the pf_* objects that were created before.
categs =
Categorie.objects.filter(visible=True).prefetch_related('souscategorie_set__theme_set__soustheme_set')
That should keep the number of queries the same, but return all of the
*_set objects, not just the visible ones (although it will still filter out
only the visible Categorie objects, remove the visible=True if you want
everything).
-James
--
You received this message because you are subscribed to the Google Groups
"Django users" 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].
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-users/CA%2Be%2BciXvfMOH2ZaMocsTZ9v1U4wScNwQ3SBQNQDXzgEFye%2BzXA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.