3

Iam trying to find out if it is possible to post and patch in the same view using the generic api method in Django rest framework. I dont think there is any generic class that allows create and update altogether, can anyone tell me if the below configuration would allow me to use post and patch method in the same view.

class QuestionList(generics.updateAPIView, generics.CreateAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer
JPG
  • 82,442
  • 19
  • 127
  • 206
skidwa
  • 103
  • 3
  • 11

2 Answers2

0

I'm not sure if that is possible but, You can create two views like this

class CreateSomeView(AuthenticatedView, CreateAPIView):

    queryset = Some.objects.all()
    serializer_class = SomeSerializer

    def create(self, request):
        serializer = self.serializer_class(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

 class SomeView(AuthenticatedView, UpdateAPIView):

    queryset = Some.objects.all()
    serializer_class = SomeSerializer

    def update(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

and two urls something like that

path('some/', CreateSomeView.as_view(), name="create-some-details"),
path('some/<int:pk>/', SomeView.as_view(), name="some-details"),

Now, from front-end you can send request with if you want to update or without id if you wish to create new. You don't have to create two serializers.

omkar yadav
  • 177
  • 5
  • 15
0

Yes, you can use them at the same time,you can create a custom view that inherits from both classes

from rest_framework import generics

class MyView(generics.CreateAPIView, generics.UpdateAPIView):
    serializer_class = MySerializer
    queryset = MyModel.objects.all()

and in you urls file:

urlpatterns = [
path('myview/', MyView.as_view(), name='myview'),
path('myview/<int:pk>/', MyView.as_view(), name='myview_update'),]

if you want to use your uuid or an identifier you have to add to your views:

    lookup_field = "uuid"

and change

    path('myview/<uuid:uuid>/', MyView.as_view(), name='myview_update'),