Created
August 2, 2017 14:52
-
-
Save codephillip/03ff3831d0ada36663bed0cc7c4bba0b to your computer and use it in GitHub Desktop.
ListCreateAPIView in django rest framework with different serializer for the GET and POST
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from rest_framework import generics, status | |
from rest_framework.response import Response | |
from rack.models import RackItem | |
from rack.serializers import RackItemSerializer, NewRackItemSerializer | |
class ListCreateRackItem(generics.ListCreateAPIView): | |
model = RackItem | |
def get_serializer_class(self): | |
if self.request.method == 'POST': | |
return NewRackItemSerializer | |
return RackItemSerializer | |
def get_queryset(self): | |
return RackItem.objects.filter(shopper=self.request.user) | |
def create(self, request, *args, **kwargs): | |
serializer = self.get_serializer(data=request.DATA) | |
if not serializer.is_valid(): | |
return Response( | |
serializer.errors, status=status.HTTP_400_BAD_REQUEST) | |
item = RackItem.objects.create( | |
shopper=request.user, | |
item_url=serializer.data['item_url'], | |
item_image_url=serializer.data['item_image_url']) | |
result = RackItemSerializer(item) | |
return Response(result.data, status=status.HTTP_201_CREATED) | |
class GetUpdateDeleteRackItem(generics.RetrieveUpdateDestroyAPIView): | |
model = RackItem | |
serializer_class = RackItemSerializer | |
def get_queryset(self): | |
return RackItem.objects.filter(shopper=self.request.user) |
GoooooooooD!
Thank you so much !!!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, on the RetrieveUpdateDestroyAPIView how do I create the class in such a way the I can create get,patch/put and delete and confirm if the objecte was deleted?
Right now that is my code but i need to make a get request to confirm if the object was deleted or update.
Thanks.