Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -
i have following viewset:
class artistprofileviewset(viewsets.modelviewset): queryset = artistprofile.objects.all() serializer_class = artistprofileserializer def perform_create(self, serializer): if serializer.is_valid(): serializer.save()
with following serializers:
class simpleartisttrackserializer(serializers.hyperlinkedmodelserializer): class meta: model = artisttrack fields = (...my fields...) class artistprofileserializer(serializers.hyperlinkedmodelserializer): owners = userserializer(many=true, required=false) tracks = simpleartisttrackserializer(many=true, required=false) class meta: model = artistprofile fields = (...my fields...)
i getting following error:
assertionerror: cannot call `.save()` after accessing `serializer.data`.if need access data before committing database inspect 'serializer.validated_data' instead.
i don't see editing serializer.data object. there missing cause edit? how can resolve error?
you don't need call is_valid
there @ all. when update serializer initialized model instance (based of pk
in route, e.g patch /artists/{3}/
). call is_valid()
if passing data serializer in:
ser = myserializer(data=request.data) # validate incoming post, etc ser.is_valid(raise_exceptions=true) data = ser.validated_data
to send additional data serializer when saving (e.g. set company, or set user, etc), use override this:
def perform_create(self, serializer): serializer.save(company=self.request.user.company)
for more details, browse drf source code , see doing. it's written , clear.
your comment indicates question much bigger. want add additional data "join" table between artists , user. can done, whole different topic , end manually managing relationship. also, read on nested writable serializers, it's big topic , more manual labor.
Comments
Post a Comment