2013-03-21 65 views
0

我有一件事,需要建議。請幫助我。爲django查詢獲得最佳匹配

我的方案是: 我有一個像ordercode 一個模型,在這個表,我有前綴像

1 | US 
12 | Canada 
13 | UK 
134 | Australia 

多。 然後,我有像12345678字符串,我需要得到這個字符串的最佳匹配。

如果用戶輸入12345678最佳匹配12 |加拿大,如果用戶輸入135678975最佳匹配13 |英國,如果用戶輸入1345676788最佳匹配134

我如何能做到這一點在Django查詢?

感謝,

回答

0

它需要多個請求檢查在給定的順序碼字符的每...

def get_matching_country(order_num): 
    i = 1 
    matching_req = Country.objects.none() 
    while true: 
     req = Country.objects.filter(country_code=order_num[:i]) 
     if res.exists(): 
      matching_req = req 
      i += 1 
     else: 
      break 

    return matching_req 
+0

感謝您的答案,在邏輯上我認爲它會返回正確的最佳匹配行,如果我們有100000行表比較,這是最好的解決方案? – voipmanvn 2013-03-21 10:53:56

+0

您將擁有與order_num中的字符數一樣多的請求。從不多。所以用11個字符串,你可以有1個請求到11。 – ornoone 2013-03-21 13:34:25

0
def match_country(request, string): 
    qs = Country.objects.filter(country_code__startswith=string) #or int(string) but you might want to write an exception if person provides a letters in that numbers. 

    return ... 

你有救了你的國家代碼字符串或整數?

+0

它無法運行,因爲如果用戶輸入1345676788,無刺在上市開始1345676788但是療法是一些誰開始13 ... – ornoone 2013-03-21 08:35:32