Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

data._mutable= True in Django rest framework

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

like image 923
Reactoo Avatar asked Mar 22 '26 08:03

Reactoo


1 Answers

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
        # …
like image 91
Willem Van Onsem Avatar answered Mar 24 '26 23:03

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!