简体   繁体   中英

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM