diff --git a/tests/models.py b/tests/models.py index c265182b7..8de6e2e0b 100644 --- a/tests/models.py +++ b/tests/models.py @@ -15,7 +15,10 @@ class RESTFrameworkModel(models.Model): class BasicModel(RESTFrameworkModel): - text = models.CharField(max_length=100, verbose_name=_("Text comes here"), help_text=_("Text description.")) + text = models.CharField( + max_length=100, + verbose_name=_("Text comes here"), + help_text=_("Text description.")) class BaseFilterableItem(RESTFrameworkModel): @@ -45,6 +48,9 @@ class ManyToManySource(RESTFrameworkModel): class ForeignKeyTarget(RESTFrameworkModel): name = models.CharField(max_length=100) + def get_first_source(self): + return self.sources.first() + class ForeignKeySource(RESTFrameworkModel): name = models.CharField(max_length=100) diff --git a/tests/test_relations_hyperlink.py b/tests/test_relations_hyperlink.py index c0642eda2..cadef5fff 100644 --- a/tests/test_relations_hyperlink.py +++ b/tests/test_relations_hyperlink.py @@ -50,6 +50,17 @@ class ForeignKeyTargetSerializer(serializers.HyperlinkedModelSerializer): fields = ('url', 'name', 'sources') +class ForeignKeyTargetCallableSourceSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = ForeignKeyTarget + fields = ('url', 'name', 'first_source') + + first_source = serializers.HyperlinkedRelatedField( + read_only=True, + source='get_first_source', + view_name='foreignkeysource-detail') + + class ForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ForeignKeySource @@ -444,3 +455,22 @@ class HyperlinkedNullableOneToOneTests(TestCase): {'url': 'http://testserver/onetoonetarget/2/', 'name': 'target-2', 'nullable_source': None}, ] self.assertEqual(serializer.data, expected) + + +class HyperlinkedRelationCallableSourceTests(TestCase): + urls = 'tests.test_relations_hyperlink' + + def setUp(self): + self.target = ForeignKeyTarget.objects.create(name='target-1') + ForeignKeySource.objects.create(name='source-1', target=self.target) + ForeignKeySource.objects.create(name='source-2', target=self.target) + + def test_relation_field_callable_source(self): + serializer = ForeignKeyTargetCallableSourceSerializer(self.target, context={'request': request}) + expected = { + 'url': 'http://testserver/foreignkeytarget/1/', + 'name': 'target-1', + 'first_source': 'http://testserver/foreignkeysource/1/', + } + with self.assertNumQueries(1): + self.assertEqual(serializer.data, expected)