Igor Belo
Igor Belo

Reputation: 738

How to avoid N+1 when counting in django

look at the following scenario:

I have an User model and an Address model that belongs to user.

In the user index, I need to show along with user's info how many addresses does the user have, but it's generating N+1 queries as everytime I call count it executes an additional query for that user id.

How can I do that? I read about select_related but I'm trying to make it in the reverse order...

In SQL it could be translated to:

SELECT user.*,
(SELECT count(*) FROM address WHERE address.user_id = user.id) AS address_count
FROM user

Is there a way to get the above SQL with django QuerySet?

Upvotes: 0

Views: 226

Answers (1)

Sayse
Sayse

Reputation: 43320

You can annotate the number of addresses, you haven't shown your models but you can use the following on your queryset

.annotate(address_count=Count('address'))
User.objects.all().annotate(address_count=Count('address'))  # Im guessing you want this

This would provide an address_count property on for each result

Docs for count

Upvotes: 3

Related Questions