Aleksei Khatkevich
Aleksei Khatkevich

Reputation: 2207

Need a small advice on the DB query optimization

Question is about code optimization, to be exact -DB query optimization:

…
…
…

filter1 = Comment.objects.filter(foreignkey_to_model1__author=self.request.user,
                                 is_active=True)
filter2 = Comment.objects.filter(foreignkey_to_model2__author=self.request.user,
                                 is_active=True)
context["comments_by_user"] = filter1.union(filter2)[: 5]
return context

I feel like this code is suck as it consist of the 2 queries + slice instead of filter on a DB level. Question – is it any chance to pack it in 1 query nicely in order to decrease load on the DB? ( and make this code less suck…) Thanks

Upvotes: 0

Views: 57

Answers (1)

Endre Both
Endre Both

Reputation: 5730

Try this:

from django.db.models import Q

filter = Comment.objects.filter(
    Q(foreignkey_to_model1__author=self.request.user) | 
    Q(foreignkey_to_model2__author=self.request.user),
    is_active=True
)[:5]

Upvotes: 2

Related Questions