views:

391

answers:

1

Hay, I'm using django 1.2 and i want to know how to count rows from a raw queryset(RawQuerySet).

The traditional .count() method doesn't work.

Heres my query

query = "SELECT *, ((ACOS(SIN(%s * PI() / 180) * SIN(lat * PI() / 180) + COS(%s * PI() / 180) * COS(lat * PI() / 180) * COS((%s - lon) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance FROM app_car WHERE price BETWEEN %s AND %s HAVING distance<=%s ORDER BY distance ASC"

cars = Car.objects.raw(query, [lat, lat, lon, min_price, max_price, miles])

return HttpResponse( cars )

And its returning

Car_Deferred_model_id_user_id object

Any ideas?

+1  A: 

Use the 'len()' function. This would give:

query = "SELECT *, ((ACOS(SIN(%s * PI() / 180) * SIN(lat * PI() / 180) + COS(%s * PI() / 180) * COS(lat * PI() / 180) * COS((%s - lon) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance FROM app_car WHERE price BETWEEN %s AND %s HAVING distance<=%s ORDER BY distance ASC"

cars = Car.objects.raw(query, [lat, lat, lon, min_price, max_price, miles])

return HttpResponse(len(list(cars))

Aside: there's some useful information on the Django 1.2 Model.objects.raw() method at: http://djangoadvent.com/1.2/smoothing-curve/

msanders
Getting this error object of type 'RawQuerySet' has no len()
dotty
len(list(cars)) seems to work after i cast the object as a list
dotty
OK, I've updated the answer accordingly.
msanders
Thanks msanders.
dotty
I'm also wondering whether it would be possible to optimise this by using 'SELECT COUNT(*)' (assuming all you need is the row count and not the rows themselves). I do not have 1.2 installed at present so cannot try it.
msanders
Ah no - that gives an InvalidQuery exception
msanders