alimp5

BookViewSet + BookSerializer

May 13th, 2021
520
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from rest_framework.permissions import IsAuthenticated
  2. from rest_framework import serializers
  3. from .serial import BookSerializer
  4. from .models import Book
  5.  
  6. class BookSerializer (serializers.ModelSerializer):
  7.     creator = serializers.ReadOnlyField (source='creator.username', allow_null=True)
  8.     class Meta:
  9.         fields = ['id', 'title', 'category', 'publisher', 'isbn', 'creator']
  10.         model = Book
  11.  
  12.  
  13.  
  14. class BookViewSet (viewsets.ModelViewSet):
  15.     """ Handles creating, reading and updating Book records """
  16.     serializer_class = BookSerializer
  17.     queryset = Book.objects.all()
  18.     authentication_classes = [drf_perms.SessionCsrfExemptAuthentication] ## disable CSRF check.
  19.  
  20.     permission_classes = (IsAuthenticated, )
  21.  
  22.     def perform_create(self, serializer):
  23.         serializer.save(creator=self.request.user)
  24.  
  25.     def perform_update(self, serializer):
  26.         serializer.save(creator=self.request.user)
  27.  
  28.     def get_queryset(self):
  29.         creator_queryset = self.queryset.filter(creator=self.request.user)
  30.         return creator_queryset
  31.  
  32.  
RAW Paste Data