[Fixed]-Fine tuning Django queryset retrieval

1👍

The most efficient way it’s use values, your query will look like this:

usernames = User.objects.filter(id__in=user_ids).values('username', 'userprofile__score', 'userprofile__avatar')

This solution will return dictionary, but you can try to use only instead of values, it’ll create django model object with specified fields, but if you will try to access not specified field it’ll generate additional query.

usernames = User.objects.filter(id__in=user_ids).select_related('userprofile').only('username', 'userprofile__score', 'userprofile__avatar')

Leave a comment