我正在使用Django 2.0.5,而我的(不可更改的)遗留sqlite数据库在几个列名中都有%符号。
CREATE TABLE tbl("name" text, "col1(%)" float);
当我使用django模型过滤器时,过滤器值作为参数应用于带有%运算符的sql字符串:
'SELECT "col1(%)" from tbl where name LIKE "%s" ' % 'John%'
遗憾的是,在这种情况下,Django没有转义%符号(在列名中),这导致字符串格式化选项出错。
有关如何解决这个问题的任何建议吗?
编辑:我认为我的问题与https://code.djangoproject.com/ticket/9055有关, 问题仅出在Django调试模式中。
这是追溯:
Traceback (most recent call last):
File "C:\svn\br_sqlite\camp2\venv\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "C:\svn\br_sqlite\camp2\venv\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\svn\br_sqlite\camp2\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\svn\br_sqlite\camp2\main\views.py", line 72, in showData
qs = validateInput(model,batch,version)
File "C:\svn\br_sqlite\camp2\main\views.py", line 36, in validateInput
return qs if len(qs) > 0 else None
File "C:\svn\br_sqlite\camp2\venv\lib\site-packages\django\db\models\query.py", line 254, in __len__
self._fetch_all()
File "C:\svn\br_sqlite\camp2\venv\lib\site-packages\django\db\models\query.py", line 1179, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\svn\br_sqlite\camp2\venv\lib\site-packages\django\db\models\query.py", line 53, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "C:\svn\br_sqlite\camp2\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1066, in execute_sql
cursor.execute(sql, params)
File "C:\svn\br_sqlite\camp2\venv\lib\site-packages\django\db\backends\utils.py", line 104, in execute
sql = self.db.ops.last_executed_query(self.cursor, sql, params)
File "C:\svn\br_sqlite\camp2\venv\lib\site-packages\django\db\backends\sqlite3\operations.py", line 143, in last_executed_query
print(sql % params)
ValueError: unsupported format character ')' (0x29) at index 3252
样本模型:
class tbl(models.Model):
name=models.TextField()
col1=models.TextField(db_column="col1(%)")
和观点:
def test(request):
a = tbl.objects.filter(name__contains='ab')
return ""
答案 0 :(得分:1)
尝试使用
'SELECT "col1(%%)" from tbl where name LIKE "%s" ' % 'John%'
Double %%
转义为单个。