data._mutable= 在 Django 休息框架中为真

data._mutable= True in Django rest framework

这个我已经看过很多次了,到处都看了,但还是不明白它到底是什么意思,它是强制性的吗?我以前没有在我的代码中使用过这个data._mutable = True or False,我不确定我是否应该使用它。

代码片段看起来有点像这样。

def update(self, request, *args, **kwargs):
        instance = self.get_object()
        data = request.data
        if data.get("something") == "null":
            data._mutable = True
            data["something"] = None
            data._mutable = False

为什么要给数据对象的私有属性_mutable赋值True或False??

如果您使用 FormParser [drf-doc] or MultiPartParser [drf-doc], or another parser that parses to a QueryDict [Django-doc] 作为解析器,那么 QueryDict 默认是 不可变的 。这意味着它将拒绝对其进行任何更改,因此您无法添加、删除或编辑 key-value 对。

通过设置 ._mutable 属性,可以防止出现错误,从而改变 QueryDict。但这不是好的做法,因为没有记录可以通过将 ._mutable 属性设置为 True 来使 QueryDict 可变。通常你使用 .copy() [Django-doc] 工作,这将 return 一个 mutable 深拷贝,所以:

def update(self, request, *args, **kwargs):
        instance = self.get_object()
        data = request.data
        if data.get('something') == 'null':
            data = data<strong>.copy()</strong>
            data['something'] = None
        # …