Skip to content

Commit d8c3dc4

Browse files
DmitriyZverevmblayman
authored andcommitted
Fixed crash when patching many-to-many relationships in Django >= 1.9 (#330)
1 parent 030b444 commit d8c3dc4

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

example/tests/test_views.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ def test_patch_to_one_relationship(self):
118118
response = self.client.get(url)
119119
assert response.data == request_data['data']
120120

121-
def test_patch_to_many_relationship(self):
121+
def test_patch_one_to_many_relationship(self):
122122
url = '/blogs/{}/relationships/entry_set'.format(self.first_entry.id)
123123
request_data = {
124124
'data': [{'type': format_resource_type('Entry'), 'id': str(self.first_entry.id)}, ]
@@ -130,6 +130,25 @@ def test_patch_to_many_relationship(self):
130130
response = self.client.get(url)
131131
assert response.data == request_data['data']
132132

133+
def test_patch_many_to_many_relationship(self):
134+
url = '/entries/{}/relationships/authors'.format(self.first_entry.id)
135+
request_data = {
136+
'data': [
137+
{
138+
'type': format_resource_type('Author'),
139+
'id': str(self.author.id)
140+
},
141+
]
142+
}
143+
response = self.client.patch(url,
144+
data=json.dumps(request_data),
145+
content_type='application/vnd.api+json')
146+
assert response.status_code == 200, response.content.decode()
147+
assert response.data == request_data['data']
148+
149+
response = self.client.get(url)
150+
assert response.data == request_data['data']
151+
133152
def test_post_to_one_relationship_should_fail(self):
134153
url = '/entries/{}/relationships/blog'.format(self.first_entry.id)
135154
request_data = {

rest_framework_json_api/views.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,8 @@ def patch(self, request, *args, **kwargs):
134134
serializer.is_valid(raise_exception=True)
135135
related_instance_or_manager.all().delete()
136136
# have to set bulk to False since data isn't saved yet
137-
if django.VERSION >= (1, 9):
137+
class_name = related_instance_or_manager.__class__.__name__
138+
if django.VERSION >= (1, 9) and class_name != 'ManyRelatedManager':
138139
related_instance_or_manager.add(*serializer.validated_data,
139140
bulk=False)
140141
else:

0 commit comments

Comments
 (0)