select_related reverse?(!)

189 views
Skip to first unread message

Andreas Bloch

unread,
May 1, 2014, 9:22:52 AM5/1/14
to django...@googlegroups.com
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?



alTus

unread,
May 1, 2014, 10:26:27 AM5/1/14
to django...@googlegroups.com
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:
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 написал:

Venkatraman S

unread,
May 1, 2014, 11:41:53 AM5/1/14
to django...@googlegroups.com
Instead of spoon-feeding you, I would recommend using DDT and check out the query that is generated and whether if it satisfies your use-case. By this, you will know how exactly select_related works and also the number of queries that gets fired in the page and what happens once you use 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...@googlegroups.com.
To post to this group, send email to django...@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/5370daf6-58d0-4573-a282-36c4a70a5937%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Andreas Bloch

unread,
May 5, 2014, 3:23:00 AM5/5/14
to django...@googlegroups.com
thanks for your input fellas, solved my problem.
Reply all
Reply to author
Forward
0 new messages