Skip to content

Instantly share code, notes, and snippets.

...
from drf_spectacular.utils import extend_schema_view
...
@extend_schema_view(list=list_users_schema)
class UsersViewSet(GenericViewSet, CreateModelMixin, ListModelMixin, RetrieveModelMixin, DestroyModelMixin):
...
# The custom schemas file
from drf_spectacular.utils import OpenApiParameter, extend_schema
list_users_schema = extend_schema(
parameters=[
OpenApiParameter(
name="username",
description=(
"Searches for the value in this query parameter returning "
list_users_schema = extend_schema(
...
)
...
@action(detail=False, methods=("GET", "POST",), pagination_class=None)
def leaders(self, request):
...
...
@action(detail=True, methods=("GET",), pagination_class=None)
def tree(self, request, pk):
...
REST_FRAMEWORK = {
...
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination",
"PAGE_SIZE": 10,
...
}
...
from rest_framework.permissions import IsAuthenticated
...
# Add this to the UsersViewSet
def get_permissions(self):
if self.action == "destroy":
return [IsAuthenticated()]
return super().get_permissions()
from drf_spectacular.utils import OpenApiParameter, extend_schema, OpenApiExample, inline_serializer
# Add this to the action in the UserViewSet
@extend_schema(
responses=inline_serializer(
name="Empty serializer for example (Ignore this).",
fields={"example": serializers.CharField()},
),
examples=[
OpenApiExample(
# Add this to the UserViewSet
@action(detail=False, methods=("GET",))
def metrics(self, request):
"""
Calculates and returns the metrics of the users.
"""
metrics_dict = get_user_metrics()
return Response(metrics_dict, status.HTTP_200_OK)
# Add this to the action
@extend_schema(
methods=("GET",),
parameters=[OpenApiParameter("username", exclude=True)],
description="Returns the list of users that have at least one user in charge.",
responses=UserListSerializer(many=True),
)
@extend_schema(
methods=("POST",),
# Add this to the UserViewSet
@action(detail=False, methods=("GET", "POST",))
def leaders(self, request):
if request.method == "GET":
leaders_ids = CustomUser.objects.filter(
leader_id__isnull=False
).distinct().values_list("leader_id", flat=True)
leaders_queryset = CustomUser.objects.filter(id__in=leaders_ids)
return_serializer = UserListSerializer(leaders_queryset, many=True)