drf-writable-nested icon indicating copy to clipboard operation
drf-writable-nested copied to clipboard

You cannot call `.save()` after accessing `serializer.data`.If you need to access data before committing to the database then inspect 'serializer.validated_data' instead.

Open iyinolu opened this issue 4 years ago • 2 comments

I get this error when i try to update a model instance with nested fields.

iyinolu avatar Sep 03 '21 23:09 iyinolu

Please show your code, this will facilitate the help.

felps-dev avatar Sep 06 '21 18:09 felps-dev

Pardon me. I have the following serializers:

class UserSerializer(UniqueFieldsMixin, serializers.ModelSerializer):

    class Meta:
        model = User
        fields = [
            "pk",'firstName', 'lastName', 'email', 'gender',
            'phoneNumber', 'dateOfBirth', 'userType',
            'dateCreated', 'lastModified'
        ]
        
class PartnerUserSerializer(
                    NestedCreateMixin, 
                    NestedUpdateMixin,
                    serializers.ModelSerializer ):

    primaryInfo = UserSerializer()
    class Meta:
        model = PartnerUser
        fields = [
            "pk", "primaryInfo", "address", "maritalStatus", 
            "nationRegNumber", "bankVerifiNum",
            "affiliates"
        ]

Here is the view class:

class PartnerUserUpdateView(UpdateAPIView):
    queryset = PartnerUser.objects.all()
    serializer_class = PartnerUserSerializer

primaryInfo field is serialized using UserSerializer. but unique validation doesnt work and i get the error mentioned in this issue.

However, overriding the following assert condition on the save method in BaseSerializer class offered a bypass:

assert not hasattr(self, '_data'), (
            "You cannot call `.save()` after accessing `serializer.data`."
            "If you need to access data before committing to the database then "
            "inspect 'serializer.validated_data' instead. "
        )

iyinolu avatar Sep 07 '21 03:09 iyinolu