class UserViewSet(BananasAPI, viewsets.ModelViewSet): name = lazy_title(_("users")) permission_classes = (DjangoModelPermissions, ) queryset = User.objects.all() class Admin: verbose_name = lazy_title(_("user")) @schema(query_serializer=UserFilterSerializer) def list(self, request): return super().list(request) def get_queryset(self): queryset = super().get_queryset() serializer = UserFilterSerializer(data=self.request.query_params) serializer.is_valid(raise_exception=True) username = serializer.validated_data.get("username") if username: queryset = queryset.filter(username__contains=username) return queryset def get_serializer_class(self): if self.action in ("retrieve", "list"): return UserDetailsSerializer elif self.action == "form": return FormSerializer else: return UserSerializer @action(detail=False) def foo(self, request): return Response("Just a simple extra list action") @action(detail=True) def bar(self, request, pk): url = reverse("bananas:v1.0:example.user-bar", kwargs={"pk": pk}) return Response( "Just a simple extra detail action, url = {url}".format(url=url)) @action(detail=True, methods=["post"], name=_("Send activation e-mail")) def send_activation_email(self, request, pk): return Response("Just another simple extra detail action") @action(detail=True, url_path="baz/(?P<x>.+)/ham/(?P<y>.+)") def baz(self, request, pk, x, y): return Response( "Just a simple extra detail action, {pk}, {x}, {y}".format(pk=pk, x=x, y=y)) @action(detail=False, methods=["get", "post"]) def form(self, request): if request.method == "GET": return Response({}) serializer = FormSerializer(data=self.request.data) serializer.is_valid(raise_exception=True) return Response(serializer.validated_data)
class PearViewSet(BananasAPI, viewsets.ModelViewSet): name = lazy_title(_("pear")) def list(self, request): return Response() class Admin: app_label = "fruit"
class FooAPI(BananasAdminAPI): name = lazy_title(_("foo")) serializer_class = HamSerializer def list(self, request): serializer = self.serializer_class(dict(spam="Skinka")) return Response(serializer.data) @action(detail=False) def bar(self, request): return Response({"bar": "baz"}) @action(detail=False, methods=["get", "post"]) def baz(self, request): return Response({"bar": "baz"})
class Admin: verbose_name = lazy_title(_("user"))