I have seen this many times and looked it everywhere but couldn't figure out what it actually means and is it mandatory? I have not used this data._mutable = True or False
in my code before and I am not sure whether I should be using it or not.
The code snippet looks somewhat like this.
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
Why do we need to assign True or False to the private attribute _mutable of data object.??
CodePudding user response:
If you use as parser a FormParser
[drf-doc] or MultiPartParser
[drf-doc], or another parser that parses to a QueryDict
[Django-doc], then the QueryDict
is by default immutable. That means that it will reject any changes to it, so you can not add, remove or edit key-value pairs.
By setting the ._mutable
attribute, you can prevent this from raising errors, and thus mutate the QueryDict
. But it is not good practice, since it is not documented that you can make the QueryDict
mutable by setting the ._mutable
attribute to True
. Usually you work with .copy()
[Django-doc] which will return a mutable deep copy, so:
def update(self, request, *args, **kwargs):
instance = self.get_object()
data = request.data
if data.get('something') == 'null':
data = data.copy()
data['something'] = None
# …