Skip to content

Bug relation name to internal value #305

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 24 additions & 7 deletions rest_framework_json_api/relations.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import collections
import inflection
import json

from rest_framework.fields import MISSING_ERROR_MESSAGE, SerializerMethodField
Expand Down Expand Up @@ -123,7 +124,13 @@ def to_internal_value(self, data):
self.fail('incorrect_type', data_type=type(data).__name__)
if not isinstance(data, dict):
self.fail('incorrect_type', data_type=type(data).__name__)

expected_relation_type = get_resource_type_from_queryset(self.queryset)
field_name = inflection.singularize(expected_relation_type)
serializer_resource_type = self.get_resource_type_from_serializer(field_name)

if serializer_resource_type is not None:
expected_relation_type = serializer_resource_type

if 'type' not in data:
self.fail('missing_type')
Expand All @@ -142,18 +149,28 @@ def to_representation(self, value):
else:
pk = value.pk

# check to see if this resource has a different resource_name when
# included and use that name
resource_type = None
root = getattr(self.parent, 'parent', self.parent)
field_name = self.field_name if self.field_name else self.parent.field_name

resource_type = self.get_resource_type_from_serializer(field_name)
if resource_type is None:
resource_type = get_resource_type_from_instance(value)

return OrderedDict([('type', resource_type), ('id', str(pk))])

def get_resource_type_from_serializer(self, field_name):
"""
Given a field_name, check if the serializer has a
corresponding included_serializer with a Meta.resource_name property

Returns the resource name or None
"""
root = getattr(self.parent, 'parent', self.parent) or self.parent
if getattr(root, 'included_serializers', None) is not None:
includes = get_included_serializers(root)
if field_name in includes.keys():
resource_type = get_resource_type_from_serializer(includes[field_name])
return get_resource_type_from_serializer(includes[field_name])

resource_type = resource_type if resource_type else get_resource_type_from_instance(value)
return OrderedDict([('type', resource_type), ('id', str(pk))])
return None

def get_choices(self, cutoff=None):
queryset = self.get_queryset()
Expand Down