如何用Django ORM查找标题包含在指定字符串中的城市?
Django ORM 查找标题包含在指定字符串中的城市
问题场景
现有City模型的精确查询示例:
In [99]: City.objects.filter(title='Hamilton') Out[99]: <QuerySet [<City: hamilton>]
给定地址字符串:
sentence = '3101A 1280 Main Street West Hamilton ON L8S 4K1'
需要实现:用Django ORM查找标题包含在该字符串中的城市。此前尝试slug__in=sentence无效,因为__in查询仅接受列表类型参数,不能直接传入字符串。
解决方案
方法一:拆分字符串为单词列表,使用title__in匹配
将地址字符串按空格拆分为单词列表,再通过title__in匹配城市标题:
# 拆分字符串为非空单词列表,去除首尾空格 words = [word.strip() for word in sentence.split() if word.strip()] # 查询标题在单词列表中的城市 matched_cities = City.objects.filter(title__in=words)
如果需要忽略大小写匹配,可以结合Lower函数统一转换为小写:
from django.db.models.functions import Lower # 把拆分后的单词转小写 lower_words = [word.strip().lower() for word in sentence.split() if word.strip()] # 匹配小写后的城市标题 matched_cities = City.objects.filter(Lower('title').in_(lower_words))
方法二:适配多单词城市名的匹配(如"New York")
如果城市名包含多个单词,拆分单个单词的方法会失效。可以先获取所有城市标题,筛选出属于地址字符串子串的标题,再进行查询:
# 获取所有城市的标题列表 all_city_titles = City.objects.values_list('title', flat=True) # 筛选出地址字符串中包含的城市标题 matched_titles = [title for title in all_city_titles if title in sentence] # 根据筛选出的标题查询城市 matched_cities = City.objects.filter(title__in=matched_titles)
注:如果城市数据量较大,建议给
title字段添加索引,或者使用数据库的全文搜索功能优化查询效率。
内容的提问来源于stack exchange,提问作者Hossein Sayyedmousavi
相关产品推荐
相关产品推荐

