[Answered ]-Incrementing counts of a model using a serializer

1👍

You use SerializerMethodField but you didn’t write any method for it. If you use SerializerMethodField, you have to write a method pointed by SerializerMethodField inside serializer. You can reach to the objects being serialized by ‘obj’ in that method.

Example:

class PostSerializer(serializers.Serializer):
    pk = serializers.IntegerField(read_only=True)
    up_vote = serializers.SerializerMethodField('cast_up_vote', write_only=True)
    down_vote = serializers.SerializerMethodField('cast_down_vote', write_only=True)
    votes = serializers.SerializerMethodField()

    def  cast_up_vote(self, obj):
        obj.up_vote += 1
        obj.save()

Please give the error traceback so that we could help better.

1👍

You may use class attribute to perform such requirement. And simply write a function with name get_<field_name> as following, and the framework will link them up.

from rest_framework import serializers

class IncrSrlz( serializers.Serializer ):
    _incr = 0

    count = serializers.SerializerMethodField()

    def get_count( self, obj ):
        self._incr += 1
        return self._incr

Resulting:

>>> IncrSrlz( range(10,20), many=True ).data
[OrderedDict([('count', 1)]), OrderedDict([('count', 2)]), OrderedDict([('count', 3)]), OrderedDict([('count', 4)]), OrderedDict([('count', 5)]), OrderedDict([('count', 6)]), OrderedDict([('count', 7)]), OrderedDict([('count', 8)]), OrderedDict([('count', 9)]), OrderedDict([('count', 10)])]

Leave a comment