如何编写允许在URL本身中输入PUT值的API

时间:2019-05-14 03:26:59

标签: django-rest-framework

我有以下课程:

Models.py

class User(models.Model):
    name = models.CharField(mex_length=50)
    email = models.EmailField(max_length=100)
    department = models.CharField(max_length=50)

    def __str__(self):
        return self.name

Views.py

class UserViewSet(viewsets.ModelViewSet):
    serializer_class = UserSerializer
    queryset = User.objects.all()

    @action(methods=['PUT'], detail=True)
    def update_department(self, request, *args, **kwargs)
        obj = self.get_object()
        ??
class DepartmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('department', )

现在我的数据库中有2个用户:

{
    "id": 1,
    "name": "abcd",
    "email": "abcd@gmail.com",
    "department": "accounts"
}
{
    "id": 2,
    "name": "efgh",
    "email": "efgh@gmail.com",
    "department": "HR"
}

我想使用api将用户2的部门更新为“帐户”,如下所示,在该处我通过api url本身传递要更新的值:

输入“ / api / user / 2 / update_department /帐户”

如何使用DRF来实现?

Urls.py

from django.conf.urls import url
from django.conf.urls import include

from rest_framework import routers

from . import views

router = routers.DefaultRouter()

router.register(r'user', views.UserViewSet, base_name='user_view')

slashless_router = routers.DefaultRouter(trailing_slash=False)
slashless_router.registry = router.registry[:]

urlpatterns = [
    url(r'', include(router.urls)),
    url(r'', include(slashless_router.urls)),
]

1 个答案:

答案 0 :(得分:1)

您不需要在update_department中定义额外的操作 ModelViewSet

只需将 HTTP PATCH 请求发送到 /api/user/2/ ,并使用JSON有效负载作为 {"department":"accounts"} < / strong>

PATCH 请求将仅使用更新您的 department 实例的 User 字段id=2


UPDATE-1

class UserViewSet(viewsets.ModelViewSet):
    serializer_class = UserSerializer
    queryset = User.objects.all()

    @action(methods=['PUT'], detail=True)
    def update_department(self, request, department, *args, **kwargs):
        obj = self.get_object()
        obj.department = department
        obj.save()
        return Response("updated")

UPDATE-2

将网址格式更改为

urlpatterns = [
    url(r'', include(router.urls)),
    url(r'', include(slashless_router.urls)),
    url(r'user/(?P<pk>[0-9]+)/update_department/(?P<department>[a-zA-Z]+)', views.UserViewSet.as_view({"put": "update_department"}))
]