2016-02-19 74 views
0

我正在做關鍵字搜索。Django模型篩選器關鍵字

當用戶輸入一個關鍵詞,它可能是 'order_num' 或 'CUSTOM_NAME',

當我做filter(Q(order_num=keyword) | Q(custom_name=keyword))

它提升一個值誤差。

因爲order_num是一個int,而custom_name是一個str。

如何使用關鍵字進行查詢?

回答

1

你可以使用int(keyword)搜索關鍵詞轉化,但由於用戶可能輸入的字符串,則需要區分:

try: 
    result = Model.objects.filter(Q(order_num=int(keyword)) | 
            Q(custom_name=keyword)) 
except ValueError: 
    # no point to filter order_num because it's not a number anyway 
    result = Model.objects.filter(custom_name=keyword) 

編輯:

即使有多個字段,它會是相同的:

# create an empty Q() object to start with 
query = Q() 

try: 
    int_keyword = int(keyword) 
    query |= Q(order_num=int_keyword) 
    query |= Q(another_int_field=int_keyword) 
except ValueError: 
    pass 
# the string query would always be executed 
query |= Q(custom_name=keyword) 
query |= Q(other_field=keyword) 

results = Model.objects.filter(query) 
+0

如果我有3個字段需要過濾,那麼我必須'嘗試很多'。所以,任何更簡單的方法來做這個查詢? –

+0

我編輯了我的答案。只需在'try except'塊中包裝所有int字段查詢就足夠了。看看這是否有道理。 –