Django: How to get count of ValuesQuerySet?

1.6k views Asked by At

I am trying to get count to work on a ValuesQuerySet. According to Django documentation

values = Model.objects.values()

will return a ValuesQuerySet which is a subclass of QuerySet

Returns a ValuesQuerySet — a QuerySet subclass that returns dictionaries when used as an 
iterable, rather than model-instance objects

This would mean that all methods of QuerySet should work on ValuesQuerySet also.

However, when I try to do it I get an exception

values = Model.objects.values()

and then somewhere in my code

v_size = size_calc(values)

def size_calc(objects)
    return objects.count()

File "/home/talha/ws/events.py", line 
246, in size_calc
return objects.count()
File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 336, in count
return self.query.get_count(using=self.db)
File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 401, in    
get_count
number = obj.get_aggregation(using=using)[None]
File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 367, in  
get_aggregation
result = query.get_compiler(using).execute_sql(SINGLE)
File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 213, in 
get_compiler
return connection.ops.compiler(self.compiler)(self, connection, using)
File "/usr/lib/python2.7/site-packages/django/db/backends/__init__.py", line 582, in 
compiler
return getattr(self._cache, compiler_name)
AttributeError: 'module' object has no attribute 'SQLAggregateCompiler'

count works seamlessly on normal QuerySets.. Could this be an issue with the backend drivers?

Update: I cannot use len after evaluating the Queryset as the data is huge and needs to be sliced before evaluation.

I am using Django with a mongodb backend. Related packages are

django==1.3.0
django-mongodb-engine==0.4.0
djangotoolbox==0.9.2
4

There are 4 answers

0
auny On BEST ANSWER

The only way I could get past this issue without making changes in the mongodb-engine was to get the count using the normal queryset. So to get the count I used

count = Model.objects.all().count()

and for the data I that wanted, I used

values = Model.objects.values('a', 'b')
7
Aswin Murugesh On

Why don't you just try len(values). That works fine

1
Yogesh dwivedi Geitpl On

Your issue caused because of mongodb aggregation functions. you can use `Model.objects.item_frequencies('field') or you can read here.

1
Arpit On

Try this:

query_list = list(query_set)
len = query_list.indexof(query_list[-1])

This method is nothing similar to len function of list. As you might know len uses loop to calculate the length but above method exploits hashing.