Joey Fran
Joey Fran

Reputation: 627

How to use a action decorator for update?

I need to update my endpoint using a action decorator. What is better way to make a action for update?

I have two serializers:

class GarageViewSet(viewsets.ModelViewSet):
    queryset = Garage.objects.all()
    serializer_class = GarageSerializer
    model = Garage

class CarViewSet(RestrictedQuerysetMixin, viewsets.ModelViewSet):
    queryset = Car.objects.all()
    serializer_class = CarSerializer
    filter_backends = (DjangoFilterBackend,)
    filterset_fields = ('color', 'model')
    model = Car

I need to receive a list payload by "car" and update the "garage" by a action. I'm trying something like this:


class GarageViewSet(viewsets.ModelViewSet):
    queryset = Garage.objects.all()
    serializer_class = GarageSerializer
    model = Garage

    @action(detail=True, methods=['put'])
        def update_car(self, request):
            queryset = Car.objects.create()
            serializer = CarSerializer(queryset, many=True)
            return Response(serializer.data)

My url file:

from django.urls import path, include
from django.conf.urls import url
from rest_framework.routers import DefaultRouter
from rest_framework.documentation import include_docs_urls

from .views import garage


router = DefaultRouter()
router.register(r"garage", garage.GarageViewSet, base_name="car")
router.register(r"car", garage.CarViewSet, base_name="car")

urlpatterns = [
    url(r"^", include(router.urls))
]

payload example:

{
    "fuel": 2,
    "model": 2,
    "color": null,
}

Does anyone got an idea for an action update??

Upvotes: 2

Views: 2673

Answers (1)

JPG
JPG

Reputation: 88499

First of all, correct your indentation,

class GarageViewSet(viewsets.ModelViewSet):
    queryset = Garage.objects.all()
    serializer_class = GarageSerializer
    model = Garage

    @action(detail=True, methods=['put'])
    def update_car(self, request):
        queryset = Car.objects.create()
        serializer = CarSerializer(queryset, many=True)
        return Response(serializer.data)

then, add the view class into your urls.py as,

path('path/to/your/put/operation/', GarageViewSet.as_view({"put": "update_car"}), name='any-name-you-like'),

Update-1


#urls.py
from django.urls import path, include
from django.conf.urls import url
from rest_framework.routers import DefaultRouter
from rest_framework.documentation import include_docs_urls

from .views import garage

router = DefaultRouter()
router.register(r"garage", garage.GarageViewSet, base_name="car")
router.register(r"car", garage.CarViewSet, base_name="car")

urlpatterns = [
                  path('garage/<int:pk>/update-card/', GarageViewSet.as_view({"put": "update_car"}), name='any-name-you-like'),
              ] + router.urls

Upvotes: 2

Related Questions