class BaseSerializer(Field):
@property
def data(self):
if not hasattr(self, '_data'):
if self.instance is not None and not getattr(self, '_errors', None):
self._data = self.to_representation(self.instance)
elif hasattr(self, '_validated_data') and not getattr(self, '_errors', None):
self._data = self.to_representation(self.validated_data)
else:
self._data = self.get_initial()
return self._data
class Serializer(BaseSerializer, metaclass=SerializerMetaclass):
@property
def data(self):
ret = super().data
return ReturnDict(ret, serializer=self)
def to_representation(self, instance):
"""
Object instance -> Dict of primitive datatypes.
"""
ret = OrderedDict()
#内部会执行bind方法
fields = self._readable_fields #找到所有的字段,然后筛选出可读的(可序列化的)。
for field in fields:
if hasattr(self, 'nb_%s' % field.field_name):
value = getattr(self, 'nb_%s' % field.field_name)(instance)
retret[field.field_name]=value
else:
attribute = field.get_attribute(instance)
ret[field.field_name] = field.to_representation(attribute)
return ret
class ModelSerializer(Serializer):
class NbModelSerializer(serializers.ModelSerializer):
gender=serializers.SerializerMethodField()
class Meta:
model=models.Role
fields=["id","name","age","gender"]
extra_kwargs={
"id":{"read_inly":True}
}
def get_gender(self,obj):
return obj.get_gender_dispalay()
ser = NbModelSerializer(instance=对象)
ser.data
ser= NbModelSerializer(data=request.data)
if ser.is_valid():
ser.save()
ser.data
#老师讲的码源也一脸蒙 所以先死记下来
#老师推荐的自定的方法
from collections import OrderedDict
from rest_framework.fields import SkipField
from rest_framework.relations import PKOnlyObject
class NbHookSerializer(object):
def to_representation(self, instance):
ret = OrderedDict()
fields = self._readable_fields
for field in fields:
if hasattr(self, 'nb_%s' % field.field_name):
value = getattr(self, 'nb_%s' % field.field_name)(instance)
ret[field.field_name] = value
else:
try:
attribute = field.get_attribute(instance)
except SkipField:
continue
check_for_none = attribute.pk if isinstance(attribute, PKOnlyObject) else attribute
if check_for_none is None:
ret[field.field_name] = None
else:
ret[field.field_name] = field.to_representation(attribute)
return ret
标签:name,自定义,field,钩子,self,ret,instance,data
From: https://www.cnblogs.com/bxj123/p/17817475.html