On 19/02/12 22:18, Yo-Yo Ma wrote:

> It doesn't seem to take advantage ``select_related`` (assuming that
> ``topping_type`` is a ``ForeignKey`` from ``Topping``. It instead
> sends a separate query for ``Topping`` and ``ToppingType``, joining
> them in Python. Is it feasible to modify ``prefetch_related`` use
> ``select_related`` when it encounters a ``ForeignKey``?
> 

It would be possible, but I think a bad idea. There are in fact some
valid cases where prefetch_related() is potentially better, even for
foreign keys, than for select_related(), for two reasons:

1) the DB could perform worse with the more complex query created by
select_related than for two separate queries.

2) the Python-side gains of prefetch_related() could outweigh the
advantages of the DB-side gains.

To explain (2) a bit more: for foreign keys, prefetch_related() could
potentially win quite a bit in terms of memory consumption and CPU time
due to the fact that the related objects are shared. If you have table A
with 100 rows and a foreign key to table B with 3 rows, and you need the
contents of both tables, with select_related you will have to create 100
A objects and 100 B objects, even though most of the B objects are the
same - this is just how it works. (This can't be fixed properly without
an identity mapper). With prefetch_related, you automatically only get 3
B objects.

So, since there are potential performance wins for prefetch_related,
this code shouldn't be clever - it should do exactly what the developer
asks. This is a good design decision anyway, especially when you are
talking about explicit performance related tweaks. If we could
automatically tell the right thing to do, neither select_related and
prefetch_related would exist at all.

Regards,

Luke


-- 
"If something is hard, it's not worth doing." (Homer Simpson)

Luke Plant || http://lukeplant.me.uk/

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

Reply via email to