(backend) search users

We need to search users by their email.
For that we will use the trigram similarity algorithm
provided by PostgreSQL. To use it we have to
activate the pg_trgm extension in postgres db.
To query the email we will use the query param
`q`.
We have another query param `document_id`, it is
necessary to exclude the users that have already
access to the document.
This commit is contained in:
Anthony LC
2024-05-29 14:48:12 +02:00
committed by Anthony LC
parent 2b456c231f
commit b4b308bda9
4 changed files with 105 additions and 13 deletions

View File

@@ -111,8 +111,7 @@ class Pagination(pagination.PageNumberPagination):
class UserViewSet(
mixins.UpdateModelMixin,
viewsets.GenericViewSet,
mixins.UpdateModelMixin, viewsets.GenericViewSet, mixins.ListModelMixin
):
"""User ViewSet"""
@@ -120,6 +119,26 @@ class UserViewSet(
queryset = models.User.objects.all()
serializer_class = serializers.UserSerializer
def get_queryset(self):
"""
Limit listed users by querying the email field with a trigram similarity
search if a query is provided.
Limit listed users by excluding users already in the document if a document_id
is provided.
"""
queryset = self.queryset
if self.action == "list":
# Exclude all users already in the given document
if document_id := self.request.GET.get("document_id", ""):
queryset = queryset.exclude(documentaccess__document_id=document_id)
# Filter users by email similarity
if query := self.request.GET.get("q", ""):
queryset = queryset.filter(email__trigram_word_similar=query)
return queryset
@decorators.action(
detail=False,
methods=["get"],