Hi. select_related is used for folloing foreign keys. So if u have, say, 
product and its producer field in it u can do smth like: 
Product.objects.select_related('producer') and in ur templates accessing 
product.producer won't hit the database.
Notice that here we have a relationship where only one producer can be 
ralated to product. But you obviously can't do it when you have multiple 
objects attached to one.
What you really need is 
prefetch_related<https://docs.djangoproject.com/en/1.7/ref/models/querysets/#prefetch-related>
:
Producer.objects.prefetch_related('review_set', 'comments_set') will 
populate product.review_set.all() and product.comments_set.all() for you.

четверг, 1 мая 2014 г., 17:22:52 UTC+4 пользователь Andreas Bloch написал:
>
> Okay, I'm a little confused here about using select_ralated...
>
> Can you only run select_related on a table that HAS a foreign key not a 
> table that IS a foreign key?
>
> What if I want to go: 
> SELECT * FROM product LEFT JOIN review on product.id = review.product_id 
> LEFT JOIN comments ON product.id = comment.product_id
>
> example models.py
>
> class Product(models.Model):
>     name =
>     
> class Review(models.Model):
>     product = models.Foreignkey(Product)
>     rating =
>
> class Comments(models.Model):
>     product = models.Foreignkey(Product)
>     text =
>     
> In my templates I want to be able to loop through all reviews and comments 
> for each product without hitting the database multiple times...
>
> How can you achieve this?
>
>
>
>

-- 
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 django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
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/6da66770-5bcc-4b27-a654-7ec2243705d2%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to