On Wed, Apr 25, 2012 at 5:58 AM, Lee Hinde <leehi...@gmail.com> wrote:
> I have a table with four or five foreign keys. Using the default form
> widgets, a foreign key is represented by a single value select.
>
> I noticed, with debug_tool_bar, that a query is being made for each
> element of each foreign key select option. Seems like it ought not
>
> I am using
>
>     classes = get_object_or_404(Classes, pk=pk)
>
> to load the record. I tried
> Classes.on_site.select_related().get(pk=pk) without any change.
>
> The question is, is this to be expected?
>

Yes. How else would it get the potential values that can be selected?

If you want to load all in one query, you can use select_related(). If
select_related() doesn't help, then your foreign keys are probably
nullable, which are not automatically loaded with select_related().

FYI, having each foreign key lookup as a separate query may not be a bad thing.
If the cardinality of the foreign keys doesn't change much (you don't
add frequently add potential new values for that foreign key), then it
is highly likely that those queries would be served from the query
cache.

If you are displaying 1 million different forms, but all their foreign
key lookups can be served from cache, do you think it would be quicker
to do 1 million queries with 5 joins in each query, with none of the
queries cached, or 5 million queries, 1 million with no joins and 4
million served from the query cache?

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to