Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
django中的复杂查询_Django_Model - Fatal编程技术网

django中的复杂查询

django中的复杂查询,django,model,Django,Model,嘿,我有一个很复杂的问题,我不能在django工作 我的模型名为Car(),我想对其执行此查询 query = "SELECT *, ((ACOS(SIN("+user_lat+" * PI() / 180) * SIN(lat * PI() / 180) + COS("+user_lat+" * PI() / 180) * COS(lat * PI() / 180) * COS(("+user_lon+" - lon) * PI() / 180)) * 180 / PI()) * 60 * 1

嘿,我有一个很复杂的问题,我不能在django工作

我的模型名为Car(),我想对其执行此查询

query = "SELECT *, ((ACOS(SIN("+user_lat+" * PI() / 180) * SIN(lat * PI() / 180) + COS("+user_lat+" * PI() / 180) * COS(lat * PI() / 180) * COS(("+user_lon+" - lon) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance FROM app_car HAVING distance<='"+miles+"' ORDER BY distance ASC"

query=“SELECT*,((ACOS(SIN(“+user\u lat+”*PI()/180)*SIN(lat*PI()/180)+COS(“+user\u lat+”*PI()/180)*COS(lat*PI()/180)*COS(“+user\u lon+”-lon)*PI()/180))*180/PI())*60*1.1515)Django ORM不支持
HAVING
HAVING
;为此,请转到DB-API。

用户raw()方法和SQL查询以获取Cars对象。

看看这个。它包含了您想要的地理查找。

您将很难在QerySet对象中返回距离值(请参阅),至少在Django 1.2之前是这样。最简单的方法是将查询移动到模型管理器中,但返回Python列表而不是查询集。您还可以查看Python的地理库来处理此类查询。

我曾试图安装GeoJango库,但它似乎有些过分。我要做的唯一基于地理位置的任务是上面列出的一个。看来django 1.2离发布不远了(定于下个月发布),我想我会把应用程序这一部分的开发推迟到四月份。谢谢Tom。
def find_cars_within_miles_from_postcode(request, miles, postcode=0):

    # create cursor for RAW query
    cursor = connection.cursor()

    # Get lat and lon from google
    lat, lon = getLonLatFromPostcode(postcode)

    # Gen query
    query = "SELECT id, ((ACOS(SIN("+lat+" * PI() / 180) * SIN(lat * PI() / 180) + COS("+lat+" * PI() / 180) * COS(lat * PI() / 180) * COS(("+lon+" - lon) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance FROM app_car HAVING distance<='"+miles+"' ORDER BY distance ASC"

    # execute the query
    cursor.execute(query)

    # grab all the IDS form the sql result
    ids = [row[0] for row in cursor.fetchall()]

    # find cars from ids
    cars = Car.objects.filter(id__in=ids)

    # return the Cars with these IDS
    return HttpResponse( cars )