Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

django - Why is custom serializer save() method not called from view?

I have a view like this:

class MyViewSet(ModelViewSet):
    # Other functions in ModelViewset

    @action(methods=['post'], url_path='publish', url_name='publish', detail=False)
    def publish_data(self, request, *args, **kwargs):
        new_data = util_to_filter_data(request.data)
        serializer = self.serializer_class(data=new_data, many=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()    # This is calling django's save() method, not the one defined by me
        return Response(serializer.data)

And my serializer:

class SomeSerializer(ModelSerializer):
    # fields
    def create(self, validated_data):
        print("in create")
        return super().create(validated_data)
    
    def save(self, **kwargs):
        print("in save")
        my_nested_field = self.validated_data.pop('my_nested_field', '')
        # Do some operations on this field, and other nested fields
        obj = None
        with transaction.atomic():
            obj = super().save(kwargs)
            # Save nested fields
        return obj

When I'm calling my serializer's save() method from my view (see the comment in view code), the save() method of django is called instead of the one defined by me, due to which I'm having issues that were handled in my save() method.

This is the traceback:

  File "/home/ubuntu18/Public/BWell/path_to_view/views.py", line 803, in publish_data
    serializer.save()
  File "/home/ubuntu18/Envs/bp_env/lib/python3.7/site-packages/rest_framework/serializers.py", line 720, in save
    self.instance = self.create(validated_data)

I wanted to perform some actions in save() before calling create(), but my flow is not reaching the save() method.

What am I doing wrong here?

P.S.: This is happening only when I am providing many=True in serializer constructor.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It is giving this error. Serializers with many=True do not support multiple update by default, only multiple create. For updates it is unclear how to deal with insertions and deletions. If you need to support multiple update, use a SomeSerializer class and override .update() so you can specify the behavior exactly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...