Skip to content
Advertisement

How to order queryset based on best match in django-rest-framework?

I am trying to order results of a query with parameters by number of matches.

For example, let’s say we have a Model:

JavaScript

With a Serializer:

JavaScript

And a ViewSet:

JavaScript

What I need to do is count every match the filter finds and then order the queryset by that number of matches for each template. For example:

I want to find all the templates that have “hello” and “world” strings in their text, image_text or headline. So I set the query parameter “search_text” to hello,world. Template with headline=”World and text=”Hello, everyone.” would have 2 matches. Another one with headline=”Hello would have 1 match. The template with 2 matches would be the first in the queryset. The same behaviour should work for tags and tags with search_text combined.

I tried to calculate these numbers right in the ViewSet and then return a sorted(queryset, key=attrgetter(‘matches’)) but encountered several issues with the DRF, like Template has no attribute ‘matches’. Or 404 when directly accessing a Template instance through API.

Any ideas?

Advertisement

Answer

Give a try to annotation where each matching pair returns 1 or 0 that are summarized into rank:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement