Sander Bakker
Sander Bakker

Reputation: 497

DRF Serializer access value of SerializerMethodField

class SimpleSerializer(serializers.HyperlinkedModelSerializer):
    value_x = serializers.SerializerMethodField('func_x')
    value_y = serializers.SerializerMethodField('func_y')

    def func_x(self, obj):
        return 0 

    def func_y(self, obj):
        value_x ?? 

In above's example is there any way to access the variable value_x within func_y whereas value_x should have the value of 0?

I've tried accessing it by just value_x and self.value_x but obviously both don't work

Upvotes: 0

Views: 1212

Answers (1)

yvesonline
yvesonline

Reputation: 4837

There's a hint in this question and its associated answers.

In your serializer you can access the other fields by using self.get_<field_name> as described in the DRF documentation, i.e. in your case (you're overriding the method names so be aware of that) it should work like this:

class SimpleSerializer(serializers.HyperlinkedModelSerializer):
    value_x = serializers.SerializerMethodField('func_x')
    value_y = serializers.SerializerMethodField('func_y')

    def func_x(self, obj):
        return 0 

    def func_y(self, obj):
        return self.func_x(obj) + 1

Side note: I like to move the SerializerMethodField function to a mixin to make it reusable and enhance maintainability, so I prefer something like the below.

class ValueXMixin():
    def get_value_x(self, obj):
        return self.func_x(obj) + 1


class ValueYMixin():
    def get_value_y(self, obj):
        return 0

class SimpleSerializer(serializers.HyperlinkedModelSerializer, ValueXMixin, ValueYMixin):
    value_x = serializers.SerializerMethodField()
    value_y = serializers.SerializerMethodField()

Upvotes: 1

Related Questions