No difference between PUT and PATCH in Django REST Framework

断了今生、忘了曾经 提交于 2021-02-08 14:59:25

问题


Here are my simple viewset and serializer classes:

class UserSerializer(ModelSerializer):

    class Meta:
        model = User
        fields = ['id', 'email', 'first_name', 'last_name']

....    

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

Suppose I want to update only my user's first name. In that case, I should use PATCH {"first_name": "New First Name"}. But at the same time, it looks like that PUT {"first_name": "New First Name"} also works the same way, though it shouldn't, because it has to validate that all the fields are specified. At least I thought so. Am I wrong? And if I'm, then what is the difference between update and partial_update in Django Rest Framework and is there any reason to keep them both (since any additional method implies additional testing, so the latter question is a bit philosophical, because looks like people find this PUT/PATCH pair really confusing). By the way, I'm using djangorestframework==3.8.2. Thank you.


回答1:


If you look at the generated serializer, you'll find that you don't have required fields. In that case, PUT and PATCH will have similar behavior. Would there be any required field, you'd see the difference.

serializer = UserSerializer(instance=user, data={"first_name": "New First"})
print(serializer)                                                                                                                                                                                  

    UserSerializer(data={'first_name': 'New First'}, instance=<User: tester>):
        id = IntegerField(label='ID', read_only=True)
        email = EmailField(allow_blank=True, label='Email address', max_length=254, required=False)
        first_name = CharField(allow_blank=True, max_length=30, required=False)
        last_name = CharField(allow_blank=True, max_length=150, required=False)


来源:https://stackoverflow.com/questions/53079614/no-difference-between-put-and-patch-in-django-rest-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!