Best way to filter a django QuerySet based on value without name (rank)
<p>So I've build a web app with django, using postgres for the database. Using <code>django.contrib.postgres.search.SearchRank</code>, I search for all recipes in my database with the word 'chocolate', and it gives me back a nice sorted QuerySet.</p>

<pre><code>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
</code></pre>

<p>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 e.g.:</p>

<pre><code>search_recipes.filter(rank_gt=0)
</code></pre>

<p>But <code>'rank'</code> is an added attribute from postgres's special <code>SearchRank</code> 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:</p>

<pre><code>x = [r for r in search_recipes if r.rank &gt; 0]
</code></pre>

<p>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 e.g. my 'rank' information that I had before).</p>

<p>Thanks!</p>

<p>you have an error in your filter, if you would like to use additional conditions to your field, you have to do it be double underscore <code>__</code></p>

<p><code>search_recipes.filter(rank__gt=0)</code></p>

python django postgresql