Test using model objects for dotted source default (#5880)

… when path components may be null.

Ref #5375, #5727
This commit is contained in:
Carlton Gibson 2018-03-16 14:51:37 +01:00 committed by GitHub
parent 0da461710a
commit 247cf096d4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 0 deletions

View File

@ -69,6 +69,17 @@ class NullableUUIDForeignKeySource(RESTFrameworkModel):
on_delete=models.CASCADE)
class NestedForeignKeySource(RESTFrameworkModel):
"""
Used for testing FK chain. A -> B -> C.
"""
name = models.CharField(max_length=100)
target = models.ForeignKey(NullableForeignKeySource, null=True, blank=True,
related_name='nested_sources',
verbose_name='Intermediate target object',
on_delete=models.CASCADE)
# OneToOne
class OneToOneTarget(RESTFrameworkModel):
name = models.CharField(max_length=100)

View File

@ -14,6 +14,9 @@ from rest_framework import fields, relations, serializers
from rest_framework.compat import unicode_repr
from rest_framework.fields import Field
from .models import (
ForeignKeyTarget, NestedForeignKeySource, NullableForeignKeySource
)
from .utils import MockObject
try:
@ -453,6 +456,22 @@ class TestDefaultOutput:
assert Serializer({'a': {'b': {'c': 'abc'}}}).data == {'c': 'abc'}
# Same test using model objects to exercise both paths in
# rest_framework.fields.get_attribute() (#5880)
class ModelSerializer(serializers.Serializer):
target = serializers.CharField(default='x', source='target.target.name')
a = NestedForeignKeySource(name="Root Object", target=None)
assert ModelSerializer(a).data == {'target': 'x'}
b = NullableForeignKeySource(name="Intermediary Object", target=None)
a.target = b
assert ModelSerializer(a).data == {'target': 'x'}
c = ForeignKeyTarget(name="Target Object")
b.target = c
assert ModelSerializer(a).data == {'target': 'Target Object'}
def test_default_for_nested_serializer(self):
class NestedSerializer(serializers.Serializer):
a = serializers.CharField(default='1')