dabadaba
dabadaba

Reputation: 9542

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.

Upvotes: 4

Views: 2894

Answers (2)

Sławomir Lenart
Sławomir Lenart

Reputation: 8397

To capture only objects having relation with things1 it can go in the query like this:

context.mymodel_set.prefetch_related(
   'things1', 'things2', 'things3'
).filter(
    things1__isnull=False
)

Upvotes: -1

Alasdair
Alasdair

Reputation: 309099

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.

Upvotes: 3

Related Questions