[Django]-Django Rest Framework Serializer Model Custom Method with parameters

11👍

You can try using the SerializerMethodField as follows if the values x and y are static:

Models

class Sample(models.Model):
    name = models.CharField(max_length=100, default=None)

    def sample_method(self, param):
        if param == 'x':
            return 1
        elif param == 'y':
            return 0

Serializers

class SampleSerializer(serializers.ModelSerializer):
    x = SerializerMethodField()
    y = SerializerMethodField()

    class Meta:
        model = Sample
        fields = ('x', 'y')

    def get_x(self, obj):
        return obj.sample_method('x')

    def get_y(self, obj):
        return obj.sample_method('y')

Another possible way of doing this is to create two separate properties (that explicitly call the sample_method with the value x or y) on your model itself and simply use the names as fields in your serializer. For example:

Models

class Sample(models.Model):
    name = models.CharField(max_length=100, default=None)

    def sample_method(self, param):
        if param == 'x':
            return 1
        elif param == 'y':
            return 0

    @property
    def x(self):
        return self.sample_method('x')

    @property
    def y(self):
        return self.sample_method('y')

Serializers

class SampleSerializer(serializers.ModelSerializer):

    class Meta:
        model = Sample
        fields = ('x', 'y')
👤Amyth

Leave a comment