【发布时间】:2017-01-24 04:15:20
【问题描述】:
所以我用 django 构建了一个 web 应用程序,使用 postgres 作为数据库。使用django.contrib.postgres.search.SearchRank,我在我的数据库中搜索所有带有“巧克力”这个词的食谱,它给了我一个很好的排序查询集。
from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank
# example code:
# searching recipe_name:
vector = SearchVector('recipe_name')
# searching for the term 'chocolate':
query = SearchQuery('chocolate')
# Recipe = recipes class in Models.py; contains 'recipe_name' column.
search_recipes = Recipe.objects.annotate(
rank=SearchRank(vector, query)
).order_by('-rank')
# this gives me a QuerySet of recipes, which have a rank attribute:
print(search_recipes[0].rank)
# 0.0607927
我不想显示匹配分数为 0 的食谱,所以我想按分数(“排名”)进行过滤。通常我会这样做,例如:
search_recipes.filter(rank_gt=0)
但'rank' 是 postgres 的特殊 SearchRank 函数的一个附加属性,它不是列名或任何东西,所以这会产生错误(`Cannot resolve keyword 'rank_gt' into field)。我可以通过以下方式得到我想要的:
x = [r for r in search_recipes if r.rank > 0]
但我只是想知道是否有更好、更简单的方法来做到这一点(因为列表理解给了我一个列表食谱,而不是一个 QuerySet --> 所以我丢失了例如我的“排名”信息,我以前有过)。
谢谢!
【问题讨论】:
-
也许您在
rank__gt中缺少双下划线?还要确保将 filter() 放在 annotate() 之后,而不是之前。
标签: python django postgresql