stelios
stelios

Reputation: 2845

DRF: Seperate fields for each CRUD operation on the same Serializer

I have a serializer that looks like this

class MySerializer(serializers.ModelSerializer):

    class Meta:
        model = MyModel
        fields = ('A', 'B')   
        # 'C' is mandatory to create the object but dont include it on GET

    def create(self, validated_data):
        # validated_data contains C ...
        instance = MyModel(**validated_data)
        print instance.__dict__  # C is None !?!?!
        instance.save()
        return instance

The view does it's job correctly and passes C inside validated_data, but when I create the MyModel it ends up without C value as shown above.

If I add 'C' in fields tuple then everything works correctly ...

Is there a sensible way to distinguish between the two cases? Writing mutliple serializers (so that each one defines different fields) seems too ugly to me.

Upvotes: 0

Views: 376

Answers (2)

glmvrml
glmvrml

Reputation: 1632

http://www.django-rest-framework.org/api-guide/fields/#write_only

class MySerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ('A', 'B', 'C')
        extra_kwargs = {'C': {'write_only': True}}

Upvotes: 3

stelios
stelios

Reputation: 2845

Ramiel was right. I had missed that property in extra_kwargs. Finally the exact solution was:

class MySerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ('A', 'B', 'C')
        extra_kwargs = {'C': {'write_only': True}}

If I don't include 'C' at fields it's not passed in validated_data.

Upvotes: -1

Related Questions