djangodjango-querysetdjango-prefetch-related

Usefulness of calling prefetch_related() without specifying lookups?


I encountered such a queryset in a project :

qs.prefetch_related().other().methods()

Is there a point having such call to prefetch_related() method without specifying any lookup?


Solution

  • Is there a point having such call to .prefetch_related() method without specifying any lookup?

    No, or at least not with a "vanilla" manager. It is possible that the user has made a subclass of the QuerySet and/or Manager that have altered the behaivor slightly.

    What I suspect is that this is based on the behavior of .select_related(…) call [Django-doc]:

    In these cases it is possible to call select_related() with no arguments. This will follow all non-null foreign keys it can find - nullable foreign keys must be specified. This is not recommended in most cases as it is likely to make the underlying query more complex, and return more data, than is actually needed.

    In that case it will thus automatically include all ForeignKeys (and OneToOneFields), and thus simply select any many-to-one or one-to-one relation in the same query.

    Likely the author had the idea - which is not that strange - that the same holds for .prefetch_related(…) [Django-doc], but it does not.

    So if you pass no parameters to .prefetch_related(…), it will not make any prefetches. It would probably also produce a lot of queries if we would just prefetch any relation.

    If there is thus no extra logic added to a custom QuerySet,.prefetch_related() acts as a no-op that will copy the QuerySet, just like .all() does.