D
D
Dobby Free2016-12-03 13:04:57
Django
Dobby Free, 2016-12-03 13:04:57

Count of filter?

When executing a Model.objects.filter(...).count() query, how many queries will be made? Will it be SELECT COUNT FROM WHERE or will it first return all the objects in an array and count them in python? And purely for verification, how to display the contents of this query in sql form? As usual query doesn't exit, count returns int.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Kitaev, 2016-12-03
@FreeDobby

count() always makes a request, and only one. len() - doesn't always make a request. The SQL content of the count query can only be seen via connection:

from django.db import connection
print(connection.queries)

If you need to know the number of objects in the selection AND iterate over it - always use len(), it works like this:
If you only need to know the number - use count()

S
sim3x, 2016-12-03
@sim3x

App for
debugging django-debug-toolbar.readthedocs.io/en/stable/pane...
When you need to look in one place - sometimes examples go to python2
stackoverflow.com/questions/971667/django-orm-how-...
The crux of the matter
https://docs.djangoproject.com/en/1.10/ref/models/...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question