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

Reactoo
  • 916
  • 2
  • 12
  • 40
  • 1
    Otherwise you can not set `data['something'] = None`: by default `request.data` is immutable, and thus does not accept altering the data. – Willem Van Onsem May 12 '22 at 19:33
  • Does this answer your question? [django - why is the request.POST object immutable?](https://stackoverflow.com/questions/12611345/django-why-is-the-request-post-object-immutable) – Andrew May 12 '22 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. – Andrew May 12 '22 at 21:11

1 Answers1

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
        # …
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • 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 May 13 '22 at 02:23
  • 1
    @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. – Willem Van Onsem May 13 '22 at 06:31
  • @Williem , Can you help me on this? https://stackoverflow.com/questions/69770813/use-of-same-serializer-class-for-post-and-get-request-in-django-rest-framework – Reactoo Jun 04 '22 at 21:38