mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-10 19:56:59 +03:00
Fixed creation of objects with reversed M2M relations
This commit is contained in:
parent
066d51faa1
commit
743224d000
|
@ -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)
|
||||
|
|
|
@ -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):
|
||||
|
|
Loading…
Reference in New Issue
Block a user