Additional field while serializing django rest framework

前端 未结 3 819
太阳男子
太阳男子 2021-01-30 12:46

I am a newbie to django rest framework and have created a sample Employee model.

My models.py:

class Employees(models.Model         


        
3条回答
  •  一个人的身影
    2021-01-30 13:17

    SerializerMethodField works fine, and we can also store data in serializer object and let method get_field_name use that.

    Example:

    class MySerializer(serializers.ModelSerializer):
        statistic = serializers.SerializerMethodField()
    
        def __init__(self, instance=None, data=serializers.empty, statistic=None, **kwargs):
            super(MySerializer, self).__init__(instance=instance, data=data, **kwargs)
            self.statistic = statistic
    
        def get_statistic(self, obj):
            if self.statistic is None:
                return serializers.empty
            return self.statistic.get(obj.id, {})
    

提交回复
热议问题