2010-02-19 87 views
1

干草,我有一个相当复杂的查询,我无法在django中工作。django中的复杂查询

我的模型被称为汽车(),我想它

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" 

任何想法执行此查询?

感谢

编辑:

我的看法是这样的

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) 

这将返回我的车在几英里的NOx量,这个效果很好。然而,原始查询返回了他们距离特定位置的距离,我认为字段名称是'距离'。

如何返回此字段'距离'与我的车对象?

回答

1

看看这个SO post。它涵盖了您想要的地理查找。

+0

请参阅编辑。 – dotty 2010-02-22 11:48:06

1

Django ORM不支持HAVING;为此,请下载到DB-API。

0

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

0

您将很难返回QerySet对象内的距离值(请参阅my question on the same thing),至少在Django 1.2之前。最简单的事情就是将查询移动到模型管理器中,但返回一个Python列表而不是查询集。您也可以查看Python的地理库来处理这类查询。

+0

我很想安装geodjango lib,但它似乎过分杀死了。我将要完成的唯一基于地理的任务是上面列出的任务。似乎Django 1.2并不遥远(预计下个月发布),我想我的应用程序的这一部分的开发将一直持续到4月。谢谢汤姆。 – dotty 2010-02-22 18:27:03