Skip to content

Fix pk-only optimization for properties #7142

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

Merged
merged 2 commits into from
Sep 3, 2020
Merged
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
9 changes: 7 additions & 2 deletions rest_framework/relations.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,13 @@ def get_attribute(self, instance):
value = attribute_instance.serializable_value(self.source_attrs[-1])
if is_simple_callable(value):
# Handle edge case where the relationship `source` argument
# points to a `get_relationship()` method on the model
value = value().pk
# points to a `get_relationship()` method on the model.
value = value()

# Handle edge case where relationship `source` argument points
# to an instance instead of a pk (e.g., a `@property`).
value = getattr(value, 'pk', value)

return PKOnlyObject(pk=value)
except AttributeError:
pass
Expand Down
9 changes: 9 additions & 0 deletions tests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,15 @@ class ManyToManySource(RESTFrameworkModel):
class ForeignKeyTarget(RESTFrameworkModel):
name = models.CharField(max_length=100)

def get_first_source(self):
"""Used for testing related field against a callable."""
return self.sources.all().order_by('pk')[0]

@property
def first_source(self):
"""Used for testing related field against a property."""
return self.sources.all().order_by('pk')[0]


class UUIDForeignKeyTarget(RESTFrameworkModel):
uuid = models.UUIDField(primary_key=True, default=uuid.uuid4)
Expand Down
47 changes: 47 additions & 0 deletions tests/test_relations_pk.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,25 @@ class Meta:
fields = ('id', 'name', 'sources')


class ForeignKeyTargetCallableSourceSerializer(serializers.ModelSerializer):
first_source = serializers.PrimaryKeyRelatedField(
source='get_first_source',
read_only=True,
)

class Meta:
model = ForeignKeyTarget
fields = ('id', 'name', 'first_source')


class ForeignKeyTargetPropertySourceSerializer(serializers.ModelSerializer):
first_source = serializers.PrimaryKeyRelatedField(read_only=True)

class Meta:
model = ForeignKeyTarget
fields = ('id', 'name', 'first_source')


class ForeignKeySourceSerializer(serializers.ModelSerializer):
class Meta:
model = ForeignKeySource
Expand Down Expand Up @@ -389,6 +408,34 @@ class Meta:
assert len(queryset) == 1


class PKRelationTests(TestCase):

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)
expected = {
'id': 1,
'name': 'target-1',
'first_source': 1,
}
with self.assertNumQueries(1):
self.assertEqual(serializer.data, expected)

def test_relation_field_property_source(self):
serializer = ForeignKeyTargetPropertySourceSerializer(self.target)
expected = {
'id': 1,
'name': 'target-1',
'first_source': 1,
}
with self.assertNumQueries(1):
self.assertEqual(serializer.data, expected)


class PKNullableForeignKeyTests(TestCase):
def setUp(self):
target = ForeignKeyTarget(name='target-1')
Expand Down