Skip to content

Partial updates and object-level validations #3070

Open
@ecordell

Description

@ecordell

The current design of rest framework doesn't seem to support object-level validations on partial updates.

Quick example:

from rest_framework import serializers

class ItemInListSerializer(serializers.Serializer):
    options=serializers.ListField()
    item=serializers.CharField()

    def validate(self, attrs):
        options = attrs.get('options')
        item = attrs.get('item')

       if item not in options:
            raise serializers.ValidationError('Item is not a valid option!')

    def update(self, instance, validated_data):
        instance.attributes = validated_data
        return instance

    def create(self, validated_data):
        # create some object

This is just a toy example, but the issue should be pretty clear: if you're creating an object with the serializer, then attrs contains both options and item, and the validations pass and the object is created. If you attempt a partial update to set item (for example), the validate method will always run before update, and will always fail, because options does not exist.

Is there any standard solution to this scenario? I could certainly write validations before anything gets to the serializer, or push them down into models, but it seems like (and correct me if I'm wrong) DRF is attempting to be that validation layer and, in theory, these validations should and could live on the serializer.

Also just to note, I'm not the only person with this problem, I found this on SO: http://stackoverflow.com/questions/28646454/django-rest-framework-partial-update-and-validation

Any help would be appreciated! Thanks!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions