gpt4 book ai didi

python - 更新对象字段的 API 调用

转载 作者:行者123 更新时间:2023-11-28 19:14:11 26 4
gpt4 key购买 nike

所以我有一个模型序列化器,它包含

class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'name', 'description')

这是我的 View 集

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

这是我的 URLs.py 文件:

from django.conf.urls import include, url
from rest_framework import routers
import views

router = DefaultRouter()
router.register('user', views.UserViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^login/', include('rest_framework.urls', namespace='rest_framework'))
]

使用序列化器,我可以让它打印出我数据库中的对象。如果我有对象 PK/ID,我希望能够更新对象的字段 idname。有没有一种方法可以使用序列化程序通过补丁/发布请求来做到这一点?我是新手,所以如果有人可以帮助我解决这个问题,我会很高兴。

我正在考虑只做一个 POST 请求,然后让它这样做:

user = User.objects.get(id=id)
user.name = "XXXXX"
user.save()

但我想使用序列化程序,使用 PATCH 请求来做到这一点。

最佳答案

下面的代码对你有帮助,

**filename : views.py**

from user.models import User
from users.serializers import UserSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status


class UserList(APIView):
"""
List all users, or create a new user.
"""
def get(self, request, format=None):
users = User.objects.all()
serializer = UserSerializer(users, many=True)
return Response(serializer.data)

def post(self, request, format=None):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class UserDetail(APIView):
"""
Retrieve, update or delete a user instance.
"""
def get_object(self, pk):
try:
return User.objects.get(pk=pk)
except User.DoesNotExist:
raise Http404

def get(self, request, pk, format=None):
user = self.get_object(pk)
serializer = UserSerializer(user)
return Response(serializer.data)

def put(self, request, pk, format=None):
user = self.get_object(pk)
serializer = UserSerializer(user, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

def delete(self, request, pk, format=None):
user = self.get_object(pk)
user.delete()
return Response(status=status.HTTP_204_NO_CONTENT)


**filename : urls.py**

from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from users import views

urlpatterns = [
url(r'^users/$', views.UserList.as_view()),
url(r'^user/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
]

urlpatterns = format_suffix_patterns(urlpatterns)

引用: http://www.django-rest-framework.org/tutorial/3-class-based-views/

关于python - 更新对象字段的 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35643685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com