2015-02-10 107 views
0

我正在使用Django 1.7。django查询多个表 - 将参数传递给查询

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

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

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

我试着使用UNION,写这样

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

一个SQL当我试图实现这个像下面,我得到了一个错误“没有足够的论据格式字符串”

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) 

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

谢谢。

+0

你可能想看看[django-watson](https://github.com/etianen/django-watson) – miraculixx 2015-02-11 00:32:58

回答

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` 

作为替代,你可以尝试使用numericparamstyle的查询。在这种情况下,单一的参数列表就足够了:

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变量应该包含在开始/结束%迹象:

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

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

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

谢谢。我已将结果集数据分配给“数据”对象,并将其分配给上下文变量并尝试在html中读取它。但我看到空行。 'data = cursor.fetchall() for res in data: print(res) context = {'data':data}'当我打印时,我看到日志中的记录。 Inhtml中,我正在读取“data”对象作为data.field1,data.field2,假定field1和field2是数据模型对象中指定的列名称。我在这里错过了什么。再次感谢 – user115391 2015-02-10 17:52:35

+0

道歉,如果我误解。我的代码如下所示: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}'。我仍然遇到同样的问题,再次感谢您的时间和帮助。 – user115391 2015-02-11 22:41:52

+0

对不起,我不小心读到您的第一条评论。您应该通过索引访问列。请参阅我的答案的第二个更新。 – catavaran 2015-02-12 07:19:20