【问题标题】:Django Postgres psycopg2 wrong script generated - quoting of table namesDjango Postgres psycopg2 生成错误脚本 - 引用表名
【发布时间】:2013-03-19 01:32:10
【问题描述】:

Django 1.5
PostgreSQL 9.2
psycopg2 2.4.6

我正在使用 QuerySet API 中的额外功能,以便能够为 Postgres 使用多维数据集扩展中的函数 - 我知道出于可移植性的原因,额外的功能不是很好,但无论如何我不会使用另一个数据库(不是在之后Postgres,不!)。所以问题是我从这段代码中得到了错误的 SQL 查询:

return self.select_related('item_place').extra(
            select={ 'distance': 'round(earth_distance(ll_to_earth(%s, %s), ll_to_earth(%s.latitude, %s.longitude))::numeric, 0)' },
            select_params=[latitude, longitude, ItemPlace._meta.db_table, ItemPlace._meta.db_table],
            where=['round(earth_distance(ll_to_earth(%s, %s), ll_to_earth(%s.latitude, %s.longitude))::numeric, 0) <= %s'],
            params=[latitude, longitude, ItemPlace._meta.db_table, ItemPlace._meta.db_table, radius])

似乎 psycopg2 用单引号包围表名,这对于 Postgres 不正确,在正在执行的脚本中我可以看到:

round(earth_distance(ll_to_earth(%s, %s), ll_to_earth('item_place'.latitude, 'item_place'.longitude))::numeric, 0)

我应该使用表名,因为我在另一个表中有纬度和经度,没有它我会得到“模糊列”错误。现在我不知道,也许我做错了,这就是为什么我得到这个错误或者它可能是 psycopg2 中的一个错误?有什么想法吗?

【问题讨论】:

    标签: django postgresql psycopg2


    【解决方案1】:

    根据the docparamsselect_params用于指示Psycopg2引用参数。它不适用于引用表名(通过双引号完成)。

    引用the doc of Psycopg2

    只有变量值应该通过这个方法绑定:不应该 用于设置表名或字段名。对于这些元素,普通字符串 在运行 execute() 之前应该使用格式化。

    此外,我们通常不会使用需要双引号作为表名的标识符ref the comment of this answer。因此直接在代码中使用表名是安全的:

    return self.select_related('item_place').extra(
            select={ 'distance': 'round(earth_distance(ll_to_earth(%s, %s), ll_to_earth({tbl}.latitude, {tbl}.longitude))::numeric, 0)'.format(tbl=ItemPlace._meta.db_table) },
            select_params=[latitude, longitude],
            where=['round(earth_distance(ll_to_earth(%s, %s), ll_to_earth({tbl}.latitude, {tbl}.longitude))::numeric, 0) <= %s'.format(tbl=ItemPlace._meta.db_table)],
            params=[latitude, longitude])
    

    【讨论】:

    • 我承认我真的错了。非常感谢您指出这一点 - 您刚刚拯救了我的一天!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    • 1970-01-01
    • 2019-06-23
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多