python - Django Rest Framework: How do I order/sort a search/filter query? -
i'm building out api django rest framework, , i'd have feature allows users search query. currently, http://127.0.0.1:8000/api/v1/species/?name=human
yields:
{ count: 3, next: null, previous: null, results: [ { id: 1, name: "humanoid", characters: [ { id: 46, name: "doctor princess" } ] }, { id: 3, name: "inhuman (overtime)", characters: [ ] }, { id: 4, name: "human", characters: [ { id: 47, name: "abraham lincoln" } ] } ] }
it's pretty close want, not quite there. i'd first object inside results
1 id
of 4 since name
field relevant search query (?name=human). (i don't care how rest ordered.) seems sorting results ascending id
. know way handle this? thanks!
here api folder's views.py
class speciesfilter(django_filters.filterset): name = django_filters.charfilter(name="name", lookup_type=("icontains")) class meta: model = species fields = ['name'] class speciesviewset(viewsets.modelviewset): queryset = species.objects.all() serializer_class = speciesserializer filter_backends = (filters.djangofilterbackend,) # search_fields = ('name',) filter_class = speciesfilter
you want sort search result relevance, in case name: "human"
should best result because matchs query word.
if it's solve problem, use raw sql query achieve goal, like:
# not tested, sql expression may vary based on database using queryset = species.objects.raw("select * species lower(name) '%human%' order char_length(name) desc limit 20")
this query find record contains "human"(ignore cases), , sort result length of name field desc. name: "human"
first item show up.
fyi, database query not best approach such kind of stuff, should go check djang-haystack project helps build search engine upon django project, fast , simple.
Comments
Post a Comment