On Wed, Sep 17, 2008 at 7:40 PM, Malcolm Tredinnick
<[EMAIL PROTECTED]> wrote:
>
>
> On Wed, 2008-09-17 at 19:30 -0500, Chris Stromberger wrote:
> > Disclaimer: Django newbie here.
> >
> > I have a join type of model access in one of my views like so:
> >
> > recent_staff_reviews =
> > StaffReview.objects.order_by('-last_update').filter(enabled =
> > True).filter(restaurant__enabled = True)[:4]
> >
> > where the StaffReview model has a foreign key to the Restaurant model.
> > So this produces a join query behind the scenes to get to the enabled
> > field on the restaurants table (I have seen the queries via a
> > "djangosnippet" I installed to show the behind-the-scene queries).
> > But the join query produced only grabs fields from the review table.
> > In the template, I access various parts of the Restaurant model via
> > the review list (so using the foreign key), like
> >
> > {% for review in recent_staff_reviews %}
> > ...
> > review.restaurant.name  ...etc
> >
> > Doing this results in a new query on the restaurant table for each
> > restaurant referenced in the review list.  But...the original query
> > already did the join and could have returned these restaurant fields
> > all in the one query.
>
> It could have, but it's more expensive by default (doing joins can often
> be done with indexes and doesn't need to necessarily read the table
> data).
>
> What you're looking for is the select_related() Queryset method.
>
> Regards,
> Malcolm
>


Thank you, that's perfect.  And makes sense to do less unless asked to
grab more.

Using select_related() reduced the queries from 12 to 3 for my page.

Thanks for the help.
-Chris

--~--~---------~--~----~------------~-------~--~----~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to