Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework Serializer Model Custom Method with parameters

Is it possible for a serializer field to use a model's custom method with parameters as its source? Something like:

models.py

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.py

class SampleSerializer(serializers.ModelSerializer):
    x = # serializer field that returns sample_method custom method with a parameter of 'x'
    y = # serializer field that returns sample_method custom method with a parameter of 'y'

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

It should return as a response something similar to:

{'x': 1, 'y': 0}
like image 988
Dean Christian Armada Avatar asked Oct 26 '25 16:10

Dean Christian Armada


1 Answers

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')
like image 94
Amyth Avatar answered Oct 29 '25 05:10

Amyth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!