fix: give priority to small usernames on autocomplete (#2604)

Basically, when the search is "joe" we first try to search for an exact
account named "joe", and fallback to normal flow when nothing matches.

fix #2591
This commit is contained in:
Yohan Boniface 2025-04-08 17:21:14 +02:00 committed by GitHub
commit dd7540596c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 27 additions and 0 deletions

View file

@ -2,6 +2,7 @@ from agnocomplete.core import AgnocompleteModel
from agnocomplete.register import register
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db.models.functions import Length
@register
@ -13,3 +14,11 @@ class AutocompleteUser(AgnocompleteModel):
data = super().item(current_item)
data["url"] = current_item.get_url()
return data
def build_extra_filtered_queryset(self, queryset, **kwargs):
order_by = []
for field_name in self.fields:
if not field_name[0].isalnum():
field_name = field_name[1:]
order_by.append(Length(field_name).asc())
return queryset.order_by(*order_by)

View file

@ -510,3 +510,21 @@ def test_can_combine_search_and_filter(client, map):
url = reverse("search")
response = client.get(url + "?q=dur&tags=bike")
assert "Blé dur" in response.content.decode()
@pytest.mark.django_db
def test_can_find_small_usernames(client):
UserFactory(username="Joe")
UserFactory(username="JoeJoe")
UserFactory(username="Joe3")
UserFactory(username="Joe57")
UserFactory(username="JoeBar")
url = "/agnocomplete/AutocompleteUser/"
response = client.get(url + "?q=joe")
data = json.loads(response.content)["data"]
assert len(data) == 5
assert data[0]["label"] == "Joe"
response = client.get(url + "?q=joej")
data = json.loads(response.content)["data"]
assert len(data) == 1
assert data[0]["label"] == "JoeJoe"