Repository URL to install this package:
|
Version:
1.0.7 ▾
|
from django.db import IntegrityError
from rest_framework import generics, viewsets
from rest_framework.exceptions import ValidationError
from rest_framework.mixins import (
CreateModelMixin,
DestroyModelMixin,
ListModelMixin,
RetrieveModelMixin,
UpdateModelMixin,
)
from pp_django.exceptions.conflict_exception import ConflictException
from pp_django.viewsets.mixins import InternalModelViewSetMixin
class CommonModelViewSet(
CreateModelMixin,
UpdateModelMixin,
ListModelMixin,
RetrieveModelMixin,
DestroyModelMixin,
viewsets.GenericViewSet,
):
pass
class InternalModelViewSet(InternalModelViewSetMixin, CommonModelViewSet, generics.ListAPIView):
http_method_names = ["get", "post", "put"]
# http://example.com/api/users?ordering=account,username
ordering_fields = []
# http://example.com/api/products?category=clothing&in_stock=True
filterset_fields = []
# http://example.com/api/users?search=russell
search_fields = []
serializer_class = None
def initial(self, request, *args, **kwargs):
super().initial(request, *args, **kwargs)
if self.serializer_class and not (
self.ordering_fields or self.filterset_fields or self.search_fields
):
model_fields = self.serializer_class.Meta.fields
self.ordering_fields = model_fields
self.filterset_fields = model_fields
self.search_fields = model_fields
def create(self, request, *args, **kwargs):
try:
return super().create(request, args, kwargs)
except (ValidationError, IntegrityError) as exc:
if isinstance(exc, ValidationError):
for key, value in exc.detail.serializer.errors.items():
if "unique" == value[0].code:
raise ConflictException(str(value[0]))
raise exc
elif isinstance(exc, IntegrityError):
raise ConflictException(str(exc).split("\n")[1])