如何使用动作装饰器进行更新?

时间:2019-03-22 18:16:26

标签: django django-rest-framework

我需要使用动作装饰器更新端点。进行更新操作的更好方法是什么?

我有两个序列化器:

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

我需要通过“汽车”接收列表有效载荷,并通过操作来更新“车库”。我正在尝试这样的事情:


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)

我的网址文件:

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))
]

有效负载示例:

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

有人知道要进行动作更新吗?

1 个答案:

答案 0 :(得分:2)

首先,纠正缩进,

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)

然后,将视图类添加为urls.py

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