获取Django查询的最佳匹配

1 投票
2 回答
557 浏览
提问于 2025-04-17 19:51

我有一件事需要建议。请帮我一下。

我的情况是:我有一个像订单代码这样的模型。

在这个表里,我有一个前缀,比如:

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

还有更多。

然后,我有一个字符串,比如12345678,我需要找到这个字符串的最佳匹配。

如果用户输入12345678,最佳匹配是12|加拿大;如果用户输入135678975,最佳匹配是13|英国;如果用户输入1345676788,最佳匹配是134。

我该如何在Django查询中实现这个呢?

谢谢!

2 个回答

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

你是把国家代码保存成字符串还是整数呢?

1

这意味着需要发出多个请求,才能检查给定订单代码中的每一个字符...

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

撰写回答