Maxim Danilov

Really?

You have created a subquery in a query and you think you are avoiding duplicate queries?

Try to see the execution plan of your query in a Database. But I'm not sure you've heard about the execution plan.

Please, try to think before write some code, espesially in Django.

And believe me:

```

Post.objects.annotate(is_liked=Count('likes__user_id')).order_by('title')

```

is much better.

"prefetch_related and select_related works on the same principle of prefetching data from the database"

i am not agree with that.

select_related adds join to other table in first queryset. On obj.init "select_related" adds data to propertly arguments of object. select_related dont changes the number of requests to DB

prefetch_related - mades a new some requests to some tables in DB. It happens strictly after the first request, where collection of objects_id created before and for this prefetch.

it is two completely different features in django, they works and use differents methods and number of queryes are different.

Maxim Danilov

Maxim Danilov

Python & Django Developer and speaker