From 67ebdd32cdab0ec9078c281d24971ccd9d119173 Mon Sep 17 00:00:00 2001 From: Aristotelis Mikropoulos Date: Wed, 17 Mar 2021 15:28:38 +0200 Subject: [PATCH] Reject PrimaryKeyRelatedField bool lookup values (#7597) * Reject PrimaryKeyRelatedField bool lookup values * Test PrimaryKeyRelatedField bool lookup rejection * Fix indentation in test --- rest_framework/relations.py | 2 ++ tests/test_relations.py | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index eaf27e1d9..cbdf23369 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -259,6 +259,8 @@ class PrimaryKeyRelatedField(RelatedField): data = self.pk_field.to_internal_value(data) queryset = self.get_queryset() try: + if isinstance(data, bool): + raise TypeError return queryset.get(pk=data) except ObjectDoesNotExist: self.fail('does_not_exist', pk_value=data) diff --git a/tests/test_relations.py b/tests/test_relations.py index 92aeecf6c..bb719a65a 100644 --- a/tests/test_relations.py +++ b/tests/test_relations.py @@ -107,6 +107,12 @@ class TestPrimaryKeyRelatedField(APISimpleTestCase): msg = excinfo.value.detail[0] assert msg == 'Incorrect type. Expected pk value, received BadType.' + def test_pk_related_lookup_bool(self): + with pytest.raises(serializers.ValidationError) as excinfo: + self.field.to_internal_value(True) + msg = excinfo.value.detail[0] + assert msg == 'Incorrect type. Expected pk value, received bool.' + def test_pk_representation(self): representation = self.field.to_representation(self.instance) assert representation == self.instance.pk