MCPcopy Index your code
hub / github.com/encode/django-rest-framework / create

Method create

rest_framework/serializers.py:976–1038  ·  view source on GitHub ↗

We have a bit of extra checking around this in order to provide descriptive messages when something goes wrong, but this method is essentially just: return ExampleModel.objects.create(**validated_data) If there are many to many fields present on the ins

(self, validated_data)

Source from the content-addressed store, hash-verified

974
975 # Default `create` and `update` behavior...
976 def create(self, validated_data):
977 """
978 We have a bit of extra checking around this in order to provide
979 descriptive messages when something goes wrong, but this method is
980 essentially just:
981
982 return ExampleModel.objects.create(**validated_data)
983
984 If there are many to many fields present on the instance then they
985 cannot be set until the model is instantiated, in which case the
986 implementation is like so:
987
988 example_relationship = validated_data.pop('example_relationship')
989 instance = ExampleModel.objects.create(**validated_data)
990 instance.example_relationship = example_relationship
991 return instance
992
993 The default implementation also does not handle nested relationships.
994 If you want to support writable nested relationships you'll need
995 to write an explicit `.create()` method.
996 """
997 raise_errors_on_nested_writes('create', self, validated_data)
998
999 ModelClass = self.Meta.model
1000
1001 # Remove many-to-many relationships from validated_data.
1002 # They are not valid arguments to the default `.create()` method,
1003 # as they require that the instance has already been saved.
1004 info = model_meta.get_field_info(ModelClass)
1005 many_to_many = {}
1006 for field_name, relation_info in info.relations.items():
1007 if relation_info.to_many and (field_name in validated_data):
1008 many_to_many[field_name] = validated_data.pop(field_name)
1009
1010 try:
1011 instance = ModelClass._default_manager.create(**validated_data)
1012 except TypeError:
1013 tb = traceback.format_exc()
1014 msg = (
1015 'Got a `TypeError` when calling `%s.%s.create()`. '
1016 'This may be because you have a writable field on the '
1017 'serializer class that is not a valid argument to '
1018 '`%s.%s.create()`. You may need to make the field '
1019 'read-only, or override the %s.create() method to handle '
1020 'this correctly.\nOriginal exception was:\n %s' %
1021 (
1022 ModelClass.__name__,
1023 ModelClass._default_manager.name,
1024 ModelClass.__name__,
1025 ModelClass._default_manager.name,
1026 self.__class__.__name__,
1027 tb
1028 )
1029 )
1030 raise TypeError(msg)
1031
1032 # Save many-to-many relationships after the instance is created.
1033 if many_to_many:

Callers

nothing calls this directly

Calls 4

get_field_infoMethod · 0.80
setMethod · 0.80
createMethod · 0.45

Tested by

no test coverage detected