ninesalt
ninesalt

Reputation: 4354

Django select_related does nothing

I have a comment model in django which contains a foreign key reference to the User model and I'm trying to lookup comments (of a certain post ID) and then join/get the user data of the author of the commment. This is what I'm doing

    result = Comment.objects.filter(post=post).select_related('user').order_by('-created_at')

When I return the result, I get the same exact object I got before I added the select_related() function. Am I missing something here?

Upvotes: 2

Views: 449

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476534

The .select_related(…) [Django-doc] function makes a JOIN in the query, and thus will use the query to load the data of the related .user object. If you do not use .select_related(…), then accessing .user of a Comment will result in an extra query. If you thus need to load all the users of N Comments, then that will take N+1 queries (and this is the famous N+1 problem).

.select_related(…) thus functionally does not change (much), it however results in a (significant) performance boost if you plan to access all the .users of the Comments.

You thus can for example print the .username of the .users in the Comment objects with:

for comment in Comment.objects.select_related('user'):
    print(comment.user.username)

If you do this without a .select_related(…) clause, it will result in a large amount of queries.

Upvotes: 4

Related Questions