diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 4f68ada68..e45016799 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -447,6 +447,13 @@ class ModelSerializer(Serializer): setattr(instance, key, val) return instance + # Reversed relation + for (obj, model) in self.opts.model._meta.get_all_related_m2m_objects_with_model(): + field_name = obj.field.related_query_name() + if field_name in attrs: + self.m2m_data[field_name] = attrs.pop(field_name) + + # Forward relation for field in self.opts.model._meta.many_to_many: if field.name in attrs: self.m2m_data[field.name] = attrs.pop(field.name) diff --git a/rest_framework/tests/pk_relations.py b/rest_framework/tests/pk_relations.py index 947098107..44ae40409 100644 --- a/rest_framework/tests/pk_relations.py +++ b/rest_framework/tests/pk_relations.py @@ -117,6 +117,24 @@ class PrimaryKeyManyToManyTests(TestCase): ] self.assertEquals(serializer.data, expected) + def test_reverse_many_to_many_create(self): + data = {'id': 4, 'name': u'target-4', 'sources': [1, 3]} + serializer = ManyToManyTargetSerializer(data=data) + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + self.assertEquals(serializer.data, data) + self.assertEqual(obj.name, u'target-4') + + # Ensure target 4 is added, and everything else is as expected + queryset = ManyToManyTarget.objects.all() + serializer = ManyToManyTargetSerializer(queryset) + expected = [ + {'id': 1, 'name': u'target-1', 'sources': [1, 2, 3]}, + {'id': 2, 'name': u'target-2', 'sources': [2, 3]}, + {'id': 3, 'name': u'target-3', 'sources': [3]}, + {'id': 4, 'name': u'target-4', 'sources': [1, 3]} + ] + self.assertEquals(serializer.data, expected) class PrimaryKeyForeignKeyTests(TestCase): def setUp(self):