[Django]-Django. Remove select_related from queryset

1👍

Can you show the code where you need this, I think refactoring is the best answer here.

If you want quick answer, entities.query.select_related = False, but it’s rather hacky (and don’t forget to restore the value if you will need select_related later).

9👍

I believe this code comments provide a relatively good answer to the general question that is asked here:

If select_related(None) is called, the list is cleared.

https://github.com/django/django/blob/stable/1.8.x/django/db/models/query.py#L735

In the general sense, if you want to do something to the entities queryset, but first remove the select_related items from it, entities.select_related(None).

However, that probably doesn’t solve your particular situation with the paginator. If you do entries.count(), then it already will remove the select_related items. If you find yourself with extra JOINs taking place, then it could be several non-ideal factors. It could be that the ORM fails to remove it because of other logic that may or may not affect the count when combined with the select_related.

As a simple example of one of these non-ideal cases, consider Foo.objects.select_related('bar').count() versus Foo.objects.select_related('bar').distinct().count(). It might be obvious to you that the original queryset does not contain multiple entries, but it is not obvious to the Django ORM. As a result, the SQL that executes contains a JOIN, and there is no universal prescription to work around that. Even applying .select_related(None) will not help you.

👤AlanSE

Leave a comment