mysql - 如何在 django2 中编写类似原始查询的查询?

标签 mysql django python-3.x

我正在尝试开发一个用户可以搜索的搜索应用程序,并且根据我的系统要求,当我尝试编写以下原始查询时,我需要避免 ORM 查询

q = request.POST.get('searchData')
    if q:
        titleInfo = Item.objects.raw("""select * from item where title like '%%s%'""", [q])

它给我这个错误

ValueError at /test
unsupported format character ''' (0x27) at index 41

如果我删除引号

"""select * from item where title like %%s%"""

它给了我以下错误

ValueError at /test
incomplete format

我的查询在 MySQL 数据库中运行良好

最佳答案

我这样解决问题

q = request.POST.get('searchData')
    query = '%'+q+'%'
    if q:
        titleInfo = Item.objects.raw("select * from item where title like %s", [query])

关于mysql - 如何在 django2 中编写类似原始查询的查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53578048/

相关文章:

mysql - SQL限制组数

php - 如何修复: Error- No database selected

django - 如何为多个 View 设置 cookie?

python - 向用户询问优先级列表,然后根据该列表对列表进行排序

php - MySQL 存储过程 [复制表 1 -> 表 2]

python - Django-从子查询中注释多个字段

django - 在MacOS 10.15上安装Psycopg2 python 3.7时出错

python - 从 Matlab 到 Numpy 的矩阵乘法转换

python - 如何在python中循环多个文件并逐一处理

MySQL-如何将一个值与另一个值分配给不同的列