1
0
mirror of https://gitlab.crans.org/bde/nk20 synced 2024-12-22 23:42:25 +00:00

Format api viewsets

This commit is contained in:
Alexandre Iooss 2020-09-03 21:47:08 +02:00
parent ff187581c9
commit d29e1d69d1
2 changed files with 30 additions and 21 deletions

View File

@ -4,6 +4,7 @@
from django.conf import settings
from django.conf.urls import url, include
from rest_framework import routers
from .viewsets import ContentTypeViewSet, UserViewSet
# Routers provide an easy way of automatically determining the URL conf.

View File

@ -64,28 +64,36 @@ class UserViewSet(ReadProtectedModelViewSet):
if "search" in self.request.GET:
pattern = self.request.GET["search"]
# We match first a user by its username, then if an alias is matched without normalization
# And finally if the normalized pattern matches a normalized alias.
# Filter with different rules
# We use union-all to keep each filter rule sorted in result
queryset = queryset.filter(
username__iregex="^" + pattern).union(
queryset.filter(
Q(note__alias__name__iregex="^" + pattern)
& ~Q(username__iregex="^" + pattern)), all=True).union(
queryset.filter(
Q(note__alias__normalized_name__iregex="^" + Alias.normalize(pattern))
& ~Q(note__alias__name__iregex="^" + pattern)
& ~Q(username__iregex="^" + pattern)), all=True).union(
queryset.filter(
Q(note__alias__normalized_name__iregex="^" + pattern.lower())
& ~Q(note__alias__normalized_name__iregex="^" + Alias.normalize(pattern))
& ~Q(note__alias__name__iregex="^" + pattern)
& ~Q(username__iregex="^" + pattern)), all=True).union(
queryset.filter(
(Q(last_name__iregex="^" + pattern) | Q(first_name__iregex="^" + pattern))
& ~Q(note__alias__normalized_name__iregex="^" + pattern.lower())
& ~Q(note__alias__normalized_name__iregex="^" + Alias.normalize(pattern))
& ~Q(note__alias__name__iregex="^" + pattern)
& ~Q(username__iregex="^" + pattern)), all=True)
# Match without normalization
note__alias__name__iregex="^" + pattern
).union(
queryset.filter(
# Match with normalization
Q(note__alias__normalized_name__iregex="^" + Alias.normalize(pattern))
& ~Q(note__alias__name__iregex="^" + pattern)
),
all=True,
).union(
queryset.filter(
# Match on lower pattern
Q(note__alias__normalized_name__iregex="^" + pattern.lower())
& ~Q(note__alias__normalized_name__iregex="^" + Alias.normalize(pattern))
& ~Q(note__alias__name__iregex="^" + pattern)
),
all=True,
).union(
queryset.filter(
# Match on firstname or lastname
(Q(last_name__iregex="^" + pattern) | Q(first_name__iregex="^" + pattern))
& ~Q(note__alias__normalized_name__iregex="^" + pattern.lower())
& ~Q(note__alias__normalized_name__iregex="^" + Alias.normalize(pattern))
& ~Q(note__alias__name__iregex="^" + pattern)
),
all=True,
)
queryset = queryset if settings.DATABASES[queryset.db]["ENGINE"] == 'django.db.backends.postgresql' \
else queryset.order_by("username")