Get number of results from Django's raw() query function

10,430

Solution 1

I presume you're talking about the raw() queryset method. That returns a queryset just like any other. So of course you can call .count() on it, just like you would on any other ORM query.

Edit Shows what happens when you don't check. As you note, .raw() returns a RawQuerySet which doesn't have a count method - and neither does it support len(). The only way to get the length is to iterate through the queryset and count them:

sum(1 for result in results)

Solution 2

You can also cast it first to a list to get the length, like so:

results = ModelName.objects.raw("select * from modelnames_modelname")
len(list(results))  #returns length

This is needed if you want to have the length or even the existence of entries in the RawQuerySet in templates as well. Just precalculate the length like above, and pass it as a parameter to the template.

Solution 3

Count Works on RawQuerySet

 

ModelName.objects.raw("select 1 as id , COUNT(*) from modelnames_modelname")

Share:
10,430
Galen
Author by

Galen

Hi

Updated on June 18, 2022

Comments

  • Galen
    Galen almost 2 years

    I'm using a raw query and i'm having trouble finding out how to get the number of results it returns. Is there a way?

    edit

    .count() doesnt work. it returns: 'RawQuerySet' object has no attribute 'count'

  • Galen
    Galen almost 14 years
    i've tried this. i get: 'RawQuerySet' object has no attribute 'count'
  • Galen
    Galen almost 14 years
    i figured there wasnt a method. Thanks a lot.
  • Ken
    Ken almost 12 years
    This forces the query to be evaluated no? If you only want the count, this is expensive.
  • Patrick Bassut
    Patrick Bassut about 10 years
    As @SK9 said: this is way expensive.
  • Dejell
    Dejell almost 8 years
    this forces the query to be evaluated no?