Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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. #149

Open
iyinolu opened this issue Sep 3, 2021 · 2 comments

Comments

@iyinolu
Copy link

iyinolu commented Sep 3, 2021

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

@felps-dev
Copy link

Please show your code, this will facilitate the help.

@iyinolu
Copy link
Author

iyinolu commented Sep 7, 2021

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. "
        )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants