2015-02-10 108 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