def__new__(cls, *args, **kwargs): # We override this method in order to automagically create # `ListSerializer` classes instead when `many=True` is set. if kwargs.pop('many', False): return cls.many_init(*args, **kwargs) returnsuper().__new__(cls, *args, **kwargs)
# If `required` is unset, then use `True` unless a default is provided. if required isNone: required = default is empty andnot read_only
# Some combinations of keyword arguments do not make sense. assertnot (read_only and write_only), NOT_READ_ONLY_WRITE_ONLY assertnot (read_only and required), NOT_READ_ONLY_REQUIRED assertnot (required and default isnot empty), NOT_REQUIRED_DEFAULT assertnot (read_only and self.__class__ == Field), USE_READONLYFIELD
defget_initial(self): """ Return a value to use when the field is being returned as a primitive value, without any object instance. """ # 完全自定义的参数,回调函数的结果为原始python数据对象 ifcallable(self.initial): return self.initial() return self.initial
1 2 3 4 5 6 7 8
classempty: """ This class is used to represent no data being provided for a given input or output value.
It is required because `None` may be a valid input or output value. """ pass
defto_representation(self, instance): """ Object instance -> Dict of primitive datatypes. """ ret = OrderedDict() # 有序的字典对象 fields = self._readable_fields
for field in fields: try: attribute = field.get_attribute(instance) # 返回该字段的原始属性值 except SkipField: continue
# We skip `to_representation` for `None` values so that fields do # not have to explicitly deal with that case. # # For related fields with `use_pk_only_optimization` we need to # resolve the pk value. check_for_none = attribute.pk ifisinstance(attribute, PKOnlyObject) else attribute # 检查该属性值是否为None,如果为None,设置None,否则将该字段值调用field基类的to_representation进行序列化 if check_for_none isNone: ret[field.field_name] = None else: ret[field.field_name] = field.to_representation(attribute)