【问题标题】:django querying multiple tables - passing parameters to the querydjango 查询多个表 - 将参数传递给查询
【发布时间】:2015-02-10 15:43:55
【问题描述】:

我正在使用 Django 1.7。

我正在尝试实现搜索功能。输入搜索词时,我需要在数据库中搜索该词的所有表和所有列(我只有 7 个表,总共可能有 40 列,数据库不是很大)。我使用 MySQL 作为数据库。

我可以查询1个表,所有列的代码如下

 query = Q(term__contains=tt) | Q(portal__contains=tt) | ......so on
 data = ABC.objects.filter(query)

我试过用UNION,写个SQL就好了

select * from table A where col1 like %s OR col2 like %s .....
 UNION
 select * from table B where col1 like %s OR col2 like %s .....

当我尝试像下面这样实现时,我收到了一个错误“格式字符串的参数不足”

cursor = connection.cursor()
cursor.execute("select * from table A where col1 like %s OR col2 like %s 
     UNION
     select * from table B where col1 like %s OR col2 like %s", tt)

那么如何为多个变量传递参数(即使在这种情况下它们是相同的)?我也尝试过多次。

谢谢。

【问题讨论】:

标签: python django django-1.7


【解决方案1】:

您应该传递参数列表。参数数量应与%s 占位符的数量相匹配:

cursor.execute("select * from table A where col1 like %s OR col2 like %s 
                UNION
                select * from table B where col1 like %s OR col2 like %s",
                [tt] * 4) # four `%s`

作为替代方案,您可以尝试使用 numeric paramstyle 进行查询。在这种情况下,单个参数列表就足够了:

cursor.execute("select * from table A where col1 like :1 OR col2 like :1 
                UNION
                select * from table B where col1 like :1 OR col2 like :1",
                [tt])

更新:注意tt 变量应该在开始/结束时包含% 符号:

tt = u'%' + string_to_find + u'%'

更新 2cursor.fetchall() 返回元组列表(不是字典),因此您应该通过索引访问此数据:

{% for row in data %}
    <div>Col1: {{ row.0 }} - Col2: {{ row.1 }}</div>
{% endfor %}

【讨论】:

  • 谢谢。我已将结果集数据分配给“数据”对象并将其分配给上下文变量并尝试在 html 中读取它。但我看到空行。 data = cursor.fetchall() for res in data: print(res) context = {'data': data} 当我打印时,我会在日志中看到记录。在html中,我将“数据”对象读取为data.field1,data.field2,假设field1和field2是数据模型对象中指定的列名。我在这里想念什么。再次感谢
  • 抱歉,如果我误解了。我的代码现在看起来像这样tt = request.GET['q'] tt = u'%' + tt + u'%' cursor = connection.cursor() cursor.execute("SELECT col1,col2 FROM TABLE_A WHERE col1 LIKE %s OR col2 LIKE %s UNION SELECT col1,col2 FROM TABLE_B WHERE col1 LIKE %s OR col2 LIKE %s [tt]*4) data_obj = cursor.fetchall() context = {'data_obj': data_obj}。我仍然遇到同样的问题。再次感谢您的时间和帮助。
  • 对不起,我不专心地阅读了你的第一条评论。您应该按索引访问列。请参阅我的答案的第二次更新。
猜你喜欢
  • 2018-03-08
  • 1970-01-01
  • 2017-07-14
  • 1970-01-01
  • 2013-04-21
  • 1970-01-01
  • 2017-09-27
  • 2014-08-23
  • 1970-01-01
相关资源
最近更新 更多