django-vote icon indicating copy to clipboard operation
django-vote copied to clipboard

Is there anyway to do a select_related() to prevent additional database hit

Open ericel opened this issue 4 years ago • 1 comments

I want to get the voters of an instance. That way I will check in the frontend if has already voted and displayed a UI according to that status. But getting the review.votes.user_ids() results in additional database hit. How to get this value without some additional database hits?

I tweaked my app, for now, to use prefetch_related('votes'). But this will still result in a 1-time additional database hit. I want to avoid that altogether if possible.

ericel avatar Jul 26 '21 11:07 ericel

You can use the annotate method, pass in a query set and the current user id, it will return a new query set with is_voted_up and is_voted_down property set on the records you are fetching. It's still an additional database hit but it's only one hit per query set, not per instance.

shellfly avatar Jul 26 '21 12:07 shellfly