(backend) annotate number of accesses on documents

The new UI will display the number of accesses on each document.

/!\ Once team accesses will be used, this will not represent the number
    of people with access anymore and will have to be improved by
    computing the number of people in each team.
This commit is contained in:
Samuel Paccoud - DINUM
2024-11-09 18:33:48 +01:00
committed by Anthony LC
parent 89d9075850
commit 774c2ce248
6 changed files with 25 additions and 6 deletions

View File

@@ -1,4 +1,5 @@
"""API endpoints"""
# pylint: disable=too-many-lines
import re
import uuid
@@ -10,6 +11,7 @@ from django.contrib.postgres.search import TrigramSimilarity
from django.core.exceptions import ValidationError
from django.core.files.storage import default_storage
from django.db.models import (
Count,
Exists,
Min,
OuterRef,
@@ -334,6 +336,9 @@ class DocumentViewSet(
queryset = super().get_queryset()
user = self.request.user
# Annotate the number of accesses associated with each document
queryset = queryset.annotate(nb_accesses=Count("accesses", distinct=True))
if not user.is_authenticated:
# If the user is not authenticated, annotate `is_favorite` as False
return queryset.annotate(is_favorite=Value(False))
@@ -360,6 +365,7 @@ class DocumentViewSet(
"""Restrict resources returned by the list endpoint"""
queryset = self.filter_queryset(self.get_queryset())
user = self.request.user
if user.is_authenticated:
queryset = queryset.filter(
Q(accesses__user=user)