aboutsummaryrefslogtreecommitdiffstats
path: root/rest_framework
diff options
context:
space:
mode:
Diffstat (limited to 'rest_framework')
-rw-r--r--rest_framework/relations.py5
-rw-r--r--rest_framework/serializers.py20
2 files changed, 23 insertions, 2 deletions
diff --git a/rest_framework/relations.py b/rest_framework/relations.py
index 474d3e75..5aa1f8bd 100644
--- a/rest_framework/relations.py
+++ b/rest_framework/relations.py
@@ -24,7 +24,10 @@ class RelatedField(Field):
# We override this method in order to automagically create
# `ManyRelation` classes instead when `many=True` is set.
if kwargs.pop('many', False):
- return ManyRelation(child_relation=cls(*args, **kwargs))
+ return ManyRelation(
+ child_relation=cls(*args, **kwargs),
+ read_only=kwargs.get('read_only', False)
+ )
return super(RelatedField, cls).__new__(cls, *args, **kwargs)
def get_queryset(self):
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
index 9f3e53fd..03e20df8 100644
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -344,7 +344,25 @@ class ModelSerializer(Serializer):
def create(self, attrs):
ModelClass = self.Meta.model
- return ModelClass.objects.create(**attrs)
+
+ # Remove many-to-many relationships from attrs.
+ # They are not valid arguments to the default `.create()` method,
+ # as they require that the instance has already been saved.
+ info = model_meta.get_field_info(ModelClass)
+ many_to_many = {}
+ for key, relation_info in info.relations.items():
+ if relation_info.to_many and (key in attrs):
+ many_to_many[key] = attrs.pop(key)
+
+ instance = ModelClass.objects.create(**attrs)
+
+ # Save many to many relationships after the instance is created.
+ if many_to_many:
+ for key, value in many_to_many.items():
+ setattr(instance, key, value)
+ instance.save()
+
+ return instance
def update(self, obj, attrs):
for attr, value in attrs.items():