Often I want to preload just some foreign keys, not all of them as
select_related() does. Other people seem to need this feature too:
http://groups.google.com/group/django-developers/browse_thread/thread/e5e0de59e8304bcd/bb93410289bc19b7
http://code.djangoproject.com/ticket/3275

My solution: I have written a function that preloads only the
requested foreign keys, and only for the objects that are already
selected. My implementation is available here:
http://trac.browsershots.org/browser/branches/shotserver-django/shotserver04/common/preload.py

My implementation has one advantage over the field parameter for
select_related: you can pass a query set that you already have, and
then you don't need any database queries again.

I think this would be nice to have in django.utils. If there's
interest, I will write documentation and unit tests and submit a
patch.

Some usage examples (see also the docstring in my implementation):

Load the required authors from the database, with a single query.
>>> preload_foreign_keys(books, author=True)

If you already have a list of authors, you can directly pass that in
too. The above is equivalent to the following example.
>>> authors = Author.objects.filter(id__in=set([book.author_id for book in 
>>> books])))
>>> preload_foreign_keys(books, author=authors)

You can preload more than one field.
>>> preload_foreign_keys(books, author=True, publisher=True)

Nested foreign keys are also supported, with double underscore syntax.
The following will load all required publishers and cities.
>>> preload_foreign_keys(books, publisher__city=True)


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-developers?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to