Best way to filter a django QuerySet based on value without name (rank)

So I've build a web app with django, using postgres for the database. Using django.contrib.postgres.search.SearchRank , I search for all recipes in my database with the word 'chocolate', and it gives me back a nice sorted QuerySet.

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

I don't want recipes whose match scores are 0 to show up, so I want to filter by score ('rank'). Usually I'd do this by eg:

search_recipes.filter(rank_gt=0)

But 'rank' is an added attribute from postgres's special SearchRank function, it's not a column name or anything, so this creates an error (`Cannot resolve keyword 'rank_gt' into field). I can get what I want with the following:

x = [r for r in search_recipes if r.rank > 0]

But I'm just wondering if there's a better, less hacky way to do this (seeing as the list comprehension gives me a list recipes, and not a QuerySet --> so I lose eg my 'rank' information that I had before).

Thanks!


你的过滤器有错误,如果你想在你的领域使用额外的条件,你必须做双下划线__

search_recipes.filter(rank__gt=0)

链接地址: http://www.djcxy.com/p/6594.html

上一篇: Django过滤器自定义查找

下一篇: 根据名称过滤django QuerySet的最佳方式(等级)