pythondjangodjango-1.8

Django prefetch related and exists


I am using prefetch_related when querying a model that have several m2m relationships:

qs = context.mymodel_set.prefetch_related('things1', 'things2', 'things3')

So that when I do this there is no need to perform an additional query to get things1, they should have been fetched already:

r = list(qs)
r[0].things1.all()

But what if I do r[0].things1.exists()? Will this generate a new query? Or will it use the prefetched information? If it generates a new query, does that mean that going for r[0].things1.all() for the purposes of existence checking is more efficient?

PS: cached information being in desync with the database does not worry me for this particular question.


Solution

  • It's easy to check the queries that Django is running for yourself.

    When I tried it, it appeared that obj.things.exists() did not cause any additional queries when things was prefetched.