4

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.??

3
  • 1
    Otherwise you can not set data['something'] = None: by default request.data is immutable, and thus does not accept altering the data. Commented May 12, 2022 at 19:33
  • Does this answer your question? django - why is the request.POST object immutable? Commented May 12, 2022 at 21:10
  • This is also mostly an opinion question. You shouldn't ever need to use it outside of exceedingly rare circumstances, so just ignore it. Pass your data to a serializer and validate it, and mutate it there. Commented May 12, 2022 at 21:11

1 Answer 1

1

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 # …
Sign up to request clarification or add additional context in comments.

3 Comments

Isn't having null as a value or None the same thing? I don't see any cases where there is a need to convert null to None.
@Reactoo: that depends on the handler of the data. There can be cases where null needs to be converted to None, although for an effective serializer, that is probably indeed not the case.
@Williem , Can you help me on this? stackoverflow.com/questions/69770813/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.