Skip to content
Snippets Groups Projects
Verified Commit 89f6e365 authored by Eliot Berriot's avatar Eliot Berriot
Browse files

Show short entries first in search results to improve UX

parent 567884b7
No related branches found
No related tags found
No related merge requests found
......@@ -9,7 +9,7 @@ from urllib.parse import parse_qs, urlencode, urlsplit, urlunsplit
from django.conf import settings
from django import urls
from django.db import transaction
from django.db import models, transaction
def rename_file(instance, field_name, new_name, allow_missing_file=False):
......@@ -139,3 +139,11 @@ def parse_meta(html):
meta = [elem for elem in tree.iter() if elem.tag in ["meta", "link"]]
return [dict([("tag", elem.tag)] + list(elem.items())) for elem in meta]
def order_for_search(qs, field):
"""
When searching, it's often more useful to have short results first,
this function will order the given qs based on the length of the given field
"""
return qs.annotate(__size=models.functions.Length(field)).order_by("__size")
......@@ -448,28 +448,29 @@ class Search(views.APIView):
"artist__name__unaccent",
]
query_obj = utils.get_query(query, search_fields)
return (
qs = (
models.Track.objects.all()
.filter(query_obj)
.select_related("artist", "album__artist")
)[: self.max_results]
)
return common_utils.order_for_search(qs, "title")[: self.max_results]
def get_albums(self, query):
search_fields = ["mbid", "title__unaccent", "artist__name__unaccent"]
query_obj = utils.get_query(query, search_fields)
return (
qs = (
models.Album.objects.all()
.filter(query_obj)
.select_related()
.prefetch_related("tracks")
)[: self.max_results]
.prefetch_related("tracks__artist")
)
return common_utils.order_for_search(qs, "title")[: self.max_results]
def get_artists(self, query):
search_fields = ["mbid", "name__unaccent"]
query_obj = utils.get_query(query, search_fields)
return (models.Artist.objects.all().filter(query_obj).with_albums())[
: self.max_results
]
qs = models.Artist.objects.all().filter(query_obj).with_albums()
return common_utils.order_for_search(qs, "name")[: self.max_results]
def get_tags(self, query):
search_fields = ["slug", "name__unaccent"]
......
Show short entries first in search results to improve UX
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment