beda-software / drf-writable-nested

Writable nested model serializer for Django REST Framework
Other
1.07k stars 116 forks source link

Remove UniqueValidator from nested serializers on create method #46

Closed Nekmo closed 6 years ago

Nekmo commented 6 years ago

Hello, first of all thank you for creating this library. I think it should be included in the core!

I'm having a problem with the nested user serializer. Validation prevents set an existing user on POST method:

HTTP 400 Bad Request
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "user": {
        "username": [
            "A user with that username already exists."
        ]
    }
}

My code:

class UserSerializer(HispaSerializerMixin, NestedCreateMixin, NestedUpdateMixin,
                     serializers.HyperlinkedModelSerializer):
    class Meta:
        model = get_user_model()
        fields = ('url', 'id', 'username', 'first_name', 'last_name', 'is_staff', 'is_active')

class GuardianUserPermSerializer(HispaSerializerMixin,
                                 NestedCreateMixin, NestedUpdateMixin,
                                 serializers.HyperlinkedModelSerializer):
    user = UserSerializer()

    class Meta:
        model = UserObjectPermission
        exclude = ()

I have investigated the matter a bit and have found a solution: https://medium.com/django-rest-framework/dealing-with-unique-constraints-in-nested-serializers-dade33b831d9

However, drop validation is a very dirty solution. The validation should be removed only if the user already exists.

Thank you.

ruscoder commented 6 years ago

The similar issue is #1

ruscoder commented 6 years ago

@Nekmo Hello! DRF describes this case here: http://www.django-rest-framework.org/api-guide/validators/#updating-nested-serializers

Nekmo commented 6 years ago

Thanks for your quick response! If this report is duplicated then it can be closed.

Would not it be possible to automatically remove the validation if the instance already exists and the unique fields are not edited?

Thank you.

ruscoder commented 6 years ago

@Nekmo We've implemented a workaround for this case:

https://github.com/beda-software/drf-writable-nested#validation-problem-for-nested-serializers-with-unique-fields-on-update

Nekmo commented 6 years ago

@ruscoder Thank you!

ruscoder commented 6 years ago

@Nekmo Don't forget to wrap save() in the first serializer into transaction.atomic to avoid partial objects creating when a validation error happens.

I'm not sure about implementing this wrapping inside the library. I'll create an issue about atomic transactions to collect feedback.