Skip to content

Reject PrimaryKeyRelatedField bool lookup values #7597

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 3 commits into from
Mar 17, 2021
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
2 changes: 2 additions & 0 deletions rest_framework/relations.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,8 @@ def to_internal_value(self, data):
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)
Expand Down
6 changes: 6 additions & 0 deletions tests/test_relations.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,12 @@ def test_pk_related_lookup_invalid_type(self):
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
Expand Down