django 查询多个表 - 将参数传递给查询

django querying multiple tables - passing parameters to the query

我正在使用 Django 1.7。

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

我可以查询1table,所有列代码如下

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

我试过用UNION,写一个SQL like

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 .....

当我尝试像下面这样实现时,我得到了一个 错误 "not enough arguments for format string"

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)

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

谢谢。

您应该传递一个参数列表。参数数量应与 %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])

UPDATE:注意 tt 变量应该在 start/end:

处包含 % 符号
tt = u'%' + string_to_find + u'%'

更新 2cursor.fetchall() returns 元组列表(不是字典)所以你应该通过索引访问这些数据:

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