Skip to content
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

Fixed #3674 -- Refactored _get_reverse_relationships() to use correct to_field. #3852

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
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
11 changes: 8 additions & 3 deletions rest_framework/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1131,9 +1131,14 @@ def build_relational_field(self, field_name, relation_info):
field_kwargs = get_relation_kwargs(field_name, relation_info)

to_field = field_kwargs.pop('to_field', None)
if to_field and not relation_info.related_model._meta.get_field(to_field).primary_key:
field_kwargs['slug_field'] = to_field
field_class = self.serializer_related_to_field
if relation_info.reverse:
if to_field and not relation_info.related_model_field.related_fields[0][1].primary_key:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any idea what the [0][1] refers to here?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will need to go back in and check what the actual values are. I really should have put a comment in there when I made the change. I'm pretty sure it's grabbing the to_field value for the related field (see the relevant django code here) but you are totally right, it is very hard to decipher just by looking at it.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

related_fields[0] is the first field in the model's from_fields list; it's a tuple of (from_field, to_field) so [1] here is referring to to_field

field_kwargs['slug_field'] = to_field
field_class = self.serializer_related_to_field
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The tests don't appear to hit this branch, so hard to verify on first sight - some more digging may be required.

Copy link

@benred42 benred42 Jul 19, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, it looks like we need to add a test case where the to_field argument on the foreign key relationship is set to a non-pk field in order to cover this branch. I hope to get a chance to work on this soon.

else:
if to_field and not relation_info.related_model._meta.get_field(to_field).primary_key:
field_kwargs['slug_field'] = to_field
field_class = self.serializer_related_to_field

# `view_name` is only valid for hyperlinked relationships.
if not issubclass(field_class, HyperlinkedRelatedField):
Expand Down
2 changes: 1 addition & 1 deletion rest_framework/utils/field_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ def get_relation_kwargs(field_name, relation_info):
"""
Creates a default instance of a flat relational field.
"""
model_field, related_model, to_many, to_field, has_through_model = relation_info
model_field, related_model, related_model_field, to_many, to_field, has_through_model, reverse = relation_info
kwargs = {
'queryset': related_model._default_manager,
'view_name': get_detail_view_name(related_model)
Expand Down
20 changes: 15 additions & 5 deletions rest_framework/utils/model_meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,11 @@
RelationInfo = namedtuple('RelationInfo', [
'model_field',
'related_model',
'related_model_field',
'to_many',
'to_field',
'has_through_model'
'has_through_model',
'reverse'
])


Expand Down Expand Up @@ -108,22 +110,26 @@ def _get_forward_relationships(opts):
forward_relations[field.name] = RelationInfo(
model_field=field,
related_model=_resolve_model(field.rel.to),
related_model_field=None,
to_many=False,
to_field=_get_to_field(field),
has_through_model=False
has_through_model=False,
reverse=False
)

# Deal with forward many-to-many relationships.
for field in [field for field in opts.many_to_many if field.serialize]:
forward_relations[field.name] = RelationInfo(
model_field=field,
related_model=_resolve_model(field.rel.to),
related_model_field=None,
to_many=True,
# manytomany do not have to_fields
to_field=None,
has_through_model=(
not field.rel.through._meta.auto_created
)
),
reverse=False
)

return forward_relations
Expand All @@ -144,9 +150,11 @@ def _get_reverse_relationships(opts):
reverse_relations[accessor_name] = RelationInfo(
model_field=None,
related_model=related,
related_model_field=relation.field,
to_many=relation.field.rel.multiple,
to_field=_get_to_field(relation.field),
has_through_model=False
has_through_model=False,
reverse=True
)

# Deal with reverse many-to-many relationships.
Expand All @@ -156,13 +164,15 @@ def _get_reverse_relationships(opts):
reverse_relations[accessor_name] = RelationInfo(
model_field=None,
related_model=related,
related_model_field=relation.field,
to_many=True,
# manytomany do not have to_fields
to_field=None,
has_through_model=(
(getattr(relation.field.rel, 'through', None) is not None) and
not relation.field.rel.through._meta.auto_created
)
),
reverse=True
)

return reverse_relations
Expand Down
68 changes: 68 additions & 0 deletions tests/test_model_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,15 @@ class ChoicesModel(models.Model):
choices_field_with_nonstandard_args = models.DecimalField(max_digits=3, decimal_places=1, choices=DECIMAL_CHOICES, verbose_name='A label')


class Issue3674ParentModel(models.Model):
title = models.CharField(max_length=64)


class Issue3674ChildModel(models.Model):
parent = models.ForeignKey(Issue3674ParentModel, related_name='children')
value = models.CharField(primary_key=True, max_length=64)


class TestModelSerializer(TestCase):
def test_create_method(self):
class TestSerializer(serializers.ModelSerializer):
Expand Down Expand Up @@ -940,3 +949,62 @@ class Meta(TestSerializer.Meta):
self.assertEqual(unicode_repr(ChildSerializer()), child_expected)
self.assertEqual(unicode_repr(TestSerializer()), test_expected)
self.assertEqual(unicode_repr(ChildSerializer()), child_expected)


class Issue3674Test(TestCase):
def test_nonPK_foreignkey_model_serializer(self):
class TestParentModel(models.Model):
title = models.CharField(max_length=64)

class TestChildModel(models.Model):
parent = models.ForeignKey(TestParentModel, related_name='children')
value = models.CharField(primary_key=True, max_length=64)

class TestChildModelSerializer(serializers.ModelSerializer):
class Meta:
model = TestChildModel
fields = ('value', 'parent')

class TestParentModelSerializer(serializers.ModelSerializer):
class Meta:
model = TestParentModel
fields = ('id', 'title', 'children')

parent_expected = dedent("""
TestParentModelSerializer():
id = IntegerField(label='ID', read_only=True)
title = CharField(max_length=64)
children = PrimaryKeyRelatedField(many=True, queryset=TestChildModel.objects.all())
""")
self.assertEqual(unicode_repr(TestParentModelSerializer()), parent_expected)

child_expected = dedent("""
TestChildModelSerializer():
value = CharField(max_length=64, validators=[<UniqueValidator(queryset=TestChildModel.objects.all())>])
parent = PrimaryKeyRelatedField(queryset=TestParentModel.objects.all())
""")
self.assertEqual(unicode_repr(TestChildModelSerializer()), child_expected)

def test_nonID_PK_foreignkey_model_serializer(self):

class TestChildModelSerializer(serializers.ModelSerializer):
class Meta:
model = Issue3674ChildModel
fields = ('value', 'parent')

class TestParentModelSerializer(serializers.ModelSerializer):
class Meta:
model = Issue3674ParentModel
fields = ('id', 'title', 'children')

parent = Issue3674ParentModel.objects.create(title='abc')
child = Issue3674ChildModel.objects.create(value='def', parent=parent)

parent_serializer = TestParentModelSerializer(parent)
child_serializer = TestChildModelSerializer(child)

parent_expected = {'children': ['def'], 'id': 1, 'title': 'abc'}
self.assertEqual(parent_serializer.data, parent_expected)

child_expected = {'parent': 1, 'value': 'def'}
self.assertEqual(child_serializer.data, child_expected)