为什么psycopg2不会为查询引用这些字符串?

时间:2010-11-24 22:47:41

标签: django django-orm psycopg2

使用psycopg2引擎用django编写应用程序。它似乎并不总是想引用我的字符串。这是一个测试用例:

>>> from pypvs.search.models import Addr2zip
>>> kwargs = {
...     'street_name__iexact': 'Common Ground',
...     'state_id__iexact': 'MT',
... }
>>> addrMatch = Addr2zip.objects.extra(
...     where = ['ctystate.zip5 = addr2zip.zip5 AND ctystate.city_name = \'%s\'' % 'Philipsburg'],
...     tables = ['ctystate', 'addr2zip']
... ).filter(**kwargs).order_by('zip5', 'street_name', 'primary_address_low', 'secondary_address_low')
>>> print addrMatch.query
SELECT "addr2zip"."addr2zip_id", "addr2zip"."zip5", "addr2zip"."zip4_low", "addr2zip"."zip4_high", "addr2zip"."street_direction", "addr2zip"."street_name", "addr2zip"."street_suffix", "addr2zip"."street_post_direction", "addr2zip"."primary_address_low", "addr2zip"."primary_address_high", "addr2zip"."primary_address_parity", "addr2zip"."secondary_address", "addr2zip"."secondary_address_low", "addr2zip"."secondary_address_high", "addr2zip"."secondary_address_parity", "addr2zip"."state_id", "addr2zip"."county_code", "addr2zip"."municipality_key", "addr2zip"."urbanization_key", "addr2zip"."record_type" FROM "addr2zip" , "ctystate" WHERE (ctystate.zip5 = addr2zip.zip5 AND ctystate.city_name = Philipsburg AND UPPER("addr2zip"."state_id"::text) = UPPER(MT)  AND UPPER("addr2zip"."street_name"::text) = UPPER(Common Ground) ) ORDER BY "addr2zip"."zip5" ASC, "addr2zip"."street_name" ASC, "addr2zip"."primary_address_low" ASC, "addr2zip"."secondary_address_low" ASC

这些字符串没有被引用的原因是什么?例如,'共同点':

AND UPPER("addr2zip"."street_name"::text) = UPPER(Common Ground)

不确定问题是在我的实现,psycopg2还是django ORM中。我很欣赏任何想法。

3 个答案:

答案 0 :(得分:1)

str(query)仅返回查询的近似表示。你想把它传递给数据库吗?

iexact发出的查询似乎与Django 1.2.3一致。以上将导致WHERE UPPER("addr2zip"."street_name"::text) = UPPER(E'Common Ground')。你使用的是哪个版本?

答案 1 :(得分:1)

要执行查询,请使用以下内容:

from django.db import DEFAULT_DB_ALIAS
queryset.query.get_compiler(DEFAULT_DB_ALIAS).as_sql()

答案 2 :(得分:0)

但你只是自己粘贴它:

where = ['ctystate.zip5 = addr2zip.zip5 AND ctystate.city_name = %s' % 'Philipsburg'],

所以你得到了用语法错误构造的查询字符串:

AND ctystate.city_name = Philipsburg