Added a test to reproduce the issue

This commit is contained in:
Ion Scerbatiuc 2015-03-13 08:10:05 -07:00
parent bdeb28944f
commit f53c6c7741
2 changed files with 37 additions and 1 deletions

View File

@ -15,7 +15,10 @@ class RESTFrameworkModel(models.Model):
class BasicModel(RESTFrameworkModel): 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): class BaseFilterableItem(RESTFrameworkModel):
@ -45,6 +48,9 @@ class ManyToManySource(RESTFrameworkModel):
class ForeignKeyTarget(RESTFrameworkModel): class ForeignKeyTarget(RESTFrameworkModel):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
def get_first_source(self):
return self.sources.first()
class ForeignKeySource(RESTFrameworkModel): class ForeignKeySource(RESTFrameworkModel):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)

View File

@ -50,6 +50,17 @@ class ForeignKeyTargetSerializer(serializers.HyperlinkedModelSerializer):
fields = ('url', 'name', 'sources') 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 ForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer):
class Meta: class Meta:
model = ForeignKeySource model = ForeignKeySource
@ -444,3 +455,22 @@ class HyperlinkedNullableOneToOneTests(TestCase):
{'url': 'http://testserver/onetoonetarget/2/', 'name': 'target-2', 'nullable_source': None}, {'url': 'http://testserver/onetoonetarget/2/', 'name': 'target-2', 'nullable_source': None},
] ]
self.assertEqual(serializer.data, expected) 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)