[Django]-Django Rest Framework Conditional Field on Serializer

13👍

Use SerializeMethodField:

class YourSerializer(serializers.ModelSerializer):
    your_conditional_field = serializers.SerializerMethodField()

    class Meta:
        model = ToSerialize

    def get_your_conditional_field(self, obj):
        # do your conditional logic here
        # and return appropriate result
        return obj.content_type > obj.object_id
👤Sam R.

20👍

None of the answers actually answer the question.

The easy thing to do is to add all the fields by default and then remove it at initialisation of the serializer depending on your condition.

In the example below, we don’t give back the emails when listing users.

class UserSerializer():

    fields = ('username', 'email')

    class Meta:
        model = User

    def __init__(self, *args, **kwargs):

        # Don't return emails when listing users
        if kwargs['context']['view'].action == 'list':
            del self.fields['email']

        super().__init__(*args, **kwargs)

4👍

The recommended way is to create custom RelatedField. Check DRF docs about generic relationships for a nice example. In the OP case it would look like this:

class ABTypeRelatedField(serializers.RelatedField):

    def to_representation(self, value):
        """
        Serialize objects to a simple textual representation.
        """
        if isinstance(value, AType):
            return 'AType: ' + value.foo
        elif isinstance(value, BType):
            return 'BType: ' + value.bar
        raise Exception('Unexpected type of content_object')


class ToSerializeSerializer(serializers.Serializer):
    content_object = ABTypeRelatedField()
👤jozo

Leave a comment