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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…