This QueryDict instance is immutable

后端 未结 5 1071
夕颜
夕颜 2020-12-30 06:10

I have a Branch model with a foreign key to account (the owner of the branch):

class Branch(SafeDeleteModel):
    _safedelete_policy = SOFT_DELETE_CASCADE
           


        
相关标签:
5条回答
  • 2020-12-30 06:20

    Do Simple:

    #views.py
    from rest_framework import generics
    
    
    class Login(generics.CreateAPIView):
        serializer_class = MySerializerClass
        def create(self, request, *args, **kwargs):
            request.data._mutable = True
            request.data['username'] = "example@mail.com"
            request.data._mutable = False
    
    #serializes.py
    from rest_framework import serializers
    
    
    class MySerializerClass(serializers.Serializer):
        username = serializers.CharField(required=False)
        password = serializers.CharField(required=False)
        class Meta:
            fields = ('username', 'password')
    
    0 讨论(0)
  • 2020-12-30 06:29

    https://docs.djangoproject.com/en/2.0/ref/request-response/#querydict-objects

    The QueryDicts at request.POST and request.GET will be immutable when accessed in a normal request/response cycle. To get a mutable version you need to use QueryDict.copy().

    0 讨论(0)
  • 2020-12-30 06:29

    I personally think it would be more elegant to write code like this.

    def create(self, request, *args, **kwargs):
        data = OrderedDict()
        data.update(request.data)
        data['account'] = request.user.account
        serializer = self.get_serializer(data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
    
    0 讨论(0)
  • 2020-12-30 06:31

    Do you know any better way to add additional fields when creating an object with django rest framework?

    The official way to provide extra data when creating/updating an object is to pass them to the serializer.save() as shown here

    0 讨论(0)
  • 2020-12-30 06:34

    As you can see in the Django documentation:

    The QueryDicts at request.POST and request.GET will be immutable when accessed in a normal request/response cycle.

    so you can use the recommendation from the same documentation:

    To get a mutable version you need to use QueryDict.copy()

    or ... use a little trick, for example, if you need to keep a reference to an object for some reason or leave the object the same:

    # remember old state
    _mutable = data._mutable
    
    # set to mutable
    data._mutable = True
    
    # сhange the values you want
    data['param_name'] = 'new value'
    
    # set mutable flag back
    data._mutable = _mutable
    

    where data it is your QueryDicts

    0 讨论(0)
提交回复
热议问题