Django REST Framework中的PUT和PATCH之间没有区别 [英] No difference between PUT and PATCH in Django REST Framework

查看:88
本文介绍了Django REST Framework中的PUT和PATCH之间没有区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我简单的视图集和序列化器类:

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

假设我只想更新用户的名字.在这种情况下,我应该使用 PATCH {"first_name":新名字"} .但同时,看起来 PUT {"first_name":"New First Name"} 也以相同的方式工作,尽管不应该这样做,因为它必须验证是否指定了所有字段.至少我是这么认为的.我错了吗?如果是的话,那么在Django Rest Framework中, update partial_update 之间有什么区别,并且有任何理由要同时保留它们(因为任何其他方法都意味着要进行额外的测试),因此后一个问题有点哲学性,因为看起来人们发现这对PUT/PATCH对确实令人困惑).顺便说一句,我正在使用 djangorestframework == 3.8.2 .谢谢你.

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.

推荐答案

如果查看生成的序列化程序,则会发现您没有必填字段.在这种情况下,PUT和PATCH将具有相似的行为.会有任何必填字段,您会看到区别.

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)

这篇关于Django REST Framework中的PUT和PATCH之间没有区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆