[英]Django Regex Field Lookup - Sort by Number of Matches for Each Item in QuerySet
我正在嘗試使用基本的regex表達式作為執行Django過濾器操作的方式。
我想從提供的查詢字符串中刪除所有無關緊要的單詞,查找標題包含任何剩余單詞的對象,然后從包含最多單詞的對象開始進行排序。
使用簡單的示例:
ignored_words = {'for', 'a', 'of', 'the', 'and', 'to', 'in'}
keywords = []
for word in query.split():
if word not in ignored_words:
keywords.append(word)
if len(keywords) > 0:
regex_str = r'(' + '|'.join(keywords) + ')'
results = MyModel.objects.filter(title__iregex=regex_str)
# Now sort them...
如果我的查詢字符串是'Delicious Apples and Bananas'
並且我有三個具有以下標題的對象:
'Apples'
'Bananas'
'Apples and Bananas'
有沒有一種有效的方法可以按關鍵字出現的次數對結果進行排序? 更具體地說,我不確定是否應該在查詢時進行某種Count()
操作,還是在之后遍歷結果並隨后進行某種其他正則表達式處理。
最后,我在過濾器之后對QuerySet執行了正則表達式操作。
def get_keyword_matches(query, regex):
compiler = re.compile(regex)
result = compiler.findall(query)
return len(result)
results = sorted(results, key=lambda my_object: get_keyword_matches(my_object.title.lower(), regex_str), reverse=True)
但是,如果有更有效的方法可以做到這一點,我很想聽聽。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.