MCPcopy
hub / github.com/encode/django-rest-framework / get_fields

Method get_fields

rest_framework/serializers.py:1068–1147  ·  view source on GitHub ↗

Return the dict of field names -> field instances that should be used for `self.fields` when instantiating the serializer.

(self)

Source from the content-addressed store, hash-verified

1066 # Determine the fields to apply...
1067
1068 def get_fields(self):
1069 """
1070 Return the dict of field names -> field instances that should be
1071 used for `self.fields` when instantiating the serializer.
1072 """
1073 if self.url_field_name is None:
1074 self.url_field_name = api_settings.URL_FIELD_NAME
1075
1076 assert hasattr(self, 'Meta'), (
1077 'Class {serializer_class} missing "Meta" attribute'.format(
1078 serializer_class=self.__class__.__name__
1079 )
1080 )
1081 assert hasattr(self.Meta, 'model'), (
1082 'Class {serializer_class} missing "Meta.model" attribute'.format(
1083 serializer_class=self.__class__.__name__
1084 )
1085 )
1086 if model_meta.is_abstract_model(self.Meta.model):
1087 raise ValueError(
1088 'Cannot use ModelSerializer with Abstract Models.'
1089 )
1090
1091 declared_fields = copy.deepcopy(self._declared_fields)
1092 model = getattr(self.Meta, 'model')
1093 depth = getattr(self.Meta, 'depth', 0)
1094
1095 if depth is not None:
1096 assert depth >= 0, "'depth' may not be negative."
1097 assert depth <= 10, "'depth' may not be greater than 10."
1098
1099 # Retrieve metadata about fields & relationships on the model class.
1100 info = model_meta.get_field_info(model)
1101 field_names = self.get_field_names(declared_fields, info)
1102
1103 # Determine any extra field arguments and hidden fields that
1104 # should be included
1105 extra_kwargs = self.get_extra_kwargs()
1106 extra_kwargs, hidden_fields = self.get_uniqueness_extra_kwargs(
1107 field_names, declared_fields, extra_kwargs
1108 )
1109
1110 # Determine the fields that should be included on the serializer.
1111 fields = {}
1112
1113 # If it's a ManyToMany field, and the default is None, then raises an exception to prevent exceptions on .set()
1114 for field_name in declared_fields.keys():
1115 if field_name in info.relations and info.relations[field_name].to_many and declared_fields[field_name].default is None:
1116 raise ValueError(
1117 f"The field '{field_name}' on serializer '{self.__class__.__name__}' is a ManyToMany field and cannot have a default value of None."
1118 )
1119
1120 for field_name in field_names:
1121 # If the field is explicitly declared on the class then use that.
1122 if field_name in declared_fields:
1123 fields[field_name] = declared_fields[field_name]
1124 continue
1125

Callers

nothing calls this directly

Calls 9

get_field_namesMethod · 0.95
get_extra_kwargsMethod · 0.95
build_fieldMethod · 0.95
include_extra_kwargsMethod · 0.95
get_field_infoMethod · 0.80
keysMethod · 0.80
getMethod · 0.45
updateMethod · 0.45

Tested by

no test coverage detected