Django在查询sql server时增加了方括号

时间:2016-07-04 15:04:02

标签: python sql-server django pyodbc freetds

我正在尝试从mac osx上的django连接到azure sql服务。 当我关注

from photo_mapper.models import Restaurant
rest_query = Restaurant.objects.all().query
print rest_query
SELECT [ate_it.restaurant].[id], [ate_it.restaurant].[name], [ate_it.restaurant].[area], [ate_it.restaurant].[city], [ate_it.restaurant].[submitter], [ate_it.restaurant].[pending], [ate_it.restaurant].[zid] FROM [ate_it.restaurant]

当我做Restaurant.objects.all()时,我得到了

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/anubhav/workspace/ate-it/venv/lib/python2.7/site-packages/django/db/models/query.py", line 234, in __repr__
    data = list(self[:REPR_OUTPUT_SIZE + 1])
  File "/Users/anubhav/workspace/ate-it/venv/lib/python2.7/site-packages/django/db/models/query.py", line 258, in __iter__
    self._fetch_all()
  File "/Users/anubhav/workspace/ate-it/venv/lib/python2.7/site-packages/django/db/models/query.py", line 1074, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/Users/anubhav/workspace/ate-it/venv/lib/python2.7/site-packages/django/db/models/query.py", line 52, in __iter__
    results = compiler.execute_sql()
  File "/Users/anubhav/workspace/ate-it/venv/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 848, in execute_sql
    cursor.execute(sql, params)
  File "/Users/anubhav/workspace/ate-it/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/Users/anubhav/workspace/ate-it/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/Users/anubhav/workspace/ate-it/venv/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/Users/anubhav/workspace/ate-it/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/Users/anubhav/workspace/ate-it/venv/lib/python2.7/site-packages/sql_server/pyodbc/base.py", line 538, in execute
    return self.cursor.execute(sql, params)
ProgrammingError: ('42S02', "[42S02] [FreeTDS][SQL Server]Invalid object name 'ate_it.restaurant'. (208) (SQLExecDirectW)")

但是,当我使用SELECT * from ate_it.restaurant手动运行查询django.db.connections时,它运行正常。 我可以阻止django添加方括号。

我的数据库设置是

DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc',
        'NAME': 'mydatabase',
        'USER' : 'myuser',
        'PASSWORD' : 'mypwd',
        'HOST' : 'myserver',
        'PORT' : '1433',
    }
}

我关注了this link以获取freetds和unixodbc setup

1 个答案:

答案 0 :(得分:1)

这是因为pyodbc。它生成表,索引或列的引用名称。 在pyodbc / operations.py中修改此函数quote_name 改变这一行
return '[%s]' % namereturn name