【问题标题】:Complex query in djangodjango中的复杂查询
【发布时间】:2010-02-19 16:53:16
【问题描述】:

嘿,我有一个非常复杂的查询,我无法在 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"

有什么想法吗?

谢谢

编辑:

我的观点是这样的

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 )

这会从 x 英里数返回我的汽车,这很好用。但是原始查询返回了它们与某个位置的距离,我认为字段名称是“距离”。

如何使用我的汽车对象返回此字段“距离”?

【问题讨论】:

    标签: django model


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      Django ORM 不支持HAVING;为此,请使用 DB-API。

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:

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

          【讨论】:

          • 我很想安装 geodjango 库,但它似乎过分了。我要做的唯一基于地理的任务是上面列出的任务。似乎 django 1.2 已经不远了(由于下个月发布)我想我将把这部分应用程序的开发推迟到四月。谢谢汤姆。
          猜你喜欢
          • 1970-01-01
          • 2011-06-08
          • 2012-10-25
          • 2013-06-09
          • 2011-10-13
          • 1970-01-01
          • 1970-01-01
          • 2017-07-13
          相关资源
          最近更新 更多