DjangoDjango·

Django count RawQuerySet

Published at 2024-08-21 18:49:27Viewed 64 times
Professional article
Please reprint with source link

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

Comments

There is no comment, let's add the first one.

弦圈热门内容

Python pip安装SSL证书错误

问题描述:正常使用pip install xxx安装会弹出错误,导致下载失败。必须增加trust host字段,才能下载成功:pip --trusted-host pypi.python.org install在cmd运行python -c "import ssl; print(ssl.get_default_verify_paths())"在默认路径里没有找到ca证书,而在Lib\site-packages\certifi文件夹中,却发现了cacert.pem文件。故而认为原因是ca证书丢失或者寻找ca证书路径出错,因此尝试修改pip的默认ca证书路径。pip.ini文件中有大量的pip配置信息,因此需要先找到该文件。在cmd通过pip -v config list发现,在多个路径中,都没有找到pip.ini文件。且了解到,pip会有一个默认的pip.conf文件(其实就是pip.ini),因此断定默认pip.ini配置文件丢失。解决办法:在python根目录中,新建pip.ini,在里面写上[global] index-url = https://mirrors.aliyun.co ...

pyttsx3运行错误

接上文Python实现语音朗读,运行示例代码时import pyttsx3 engine = pyttsx3.init() engine.say('开车不规范,亲人两行泪,I love China') engine.runAndWait()弹出以下错误:经过检查,pywin32等库都已经安装好了。尝试使用win32com库替代pyttsx3,结果仍然报错,报错内容为win32 api。之后又尝试了几种办法,仍然都是跟win32有关的报错。因为之前pip安装总是SSL报错,刚开始以为是SSL报错导致安装出错。但是修复SSL报错问题后(见Python pip安装SSL证书错误),该问题仍然没解决。最后经过了解,可能是pywin32版本过高所导致。一般需要将pywin32版本控制在305以下,可以使用225或者226这样的低版本。于是使用pip下载对应版本pip install pypiwin32 pip install pywin32 == 225然而,下载时发现已经没有225版本可以下载。因此另寻办法。最终,发现是pywin32安装的版本有问题,导致包虽然有了,但是却无法识别,导致出现N ...

Get connected with us on social networks! Twitter

©2024 Guangzhou Sinephony Technology Co., Ltd All Rights Reserved