Django count RawQuerySet
Question
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?
Answer 1
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/ [Looks like that site might have expired, but the Internet Archive has it at: http://web.archive.org/web/20110513122309/http://djangoadvent.com/1.2/smoothing-curve/ ]
The content is from StackOverflow which is translated and used in accordance with the CCBY-SA 4.0 license agreement. Original link: Django count RawQuerySet
0 人喜欢
There is no comment, let's add the first one.