Skip to content

Commit eff97ef

Browse files
authored
Don't catch exceptions in get_queryset (encode#7480)
In the `to_internal_value` method of the primary key and slug related fields, `TypeError`s and `ValueError`s are caught from `self.get_queryset().get(...)` and presented to the user. This works fine for most cases, but can cause problems if the exception is coming from `self.get_queryset()` rather than from the `.get(...)`. It means errors in the `get_queryset` method can be hidden and presented back to the user as though, for example, the input provided to the `to_internal_value` was the wrong type, whereas in reality there's a bug in the `get_queryset` method and therefore it should bubble up and be exposed as a server error. I've decided to fix this because twice now I've had to debug why I'm seeing `invalid_type` errors from my serializer (errors like `wrong pk type - int` when the `pk` type on my model is `int`) when the real problem was a bug in my custom `get_queryset` method.
1 parent fd5e1a7 commit eff97ef

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

rest_framework/relations.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -257,8 +257,9 @@ def use_pk_only_optimization(self):
257257
def to_internal_value(self, data):
258258
if self.pk_field is not None:
259259
data = self.pk_field.to_internal_value(data)
260+
queryset = self.get_queryset()
260261
try:
261-
return self.get_queryset().get(pk=data)
262+
return queryset.get(pk=data)
262263
except ObjectDoesNotExist:
263264
self.fail('does_not_exist', pk_value=data)
264265
except (TypeError, ValueError):
@@ -454,8 +455,9 @@ def __init__(self, slug_field=None, **kwargs):
454455
super().__init__(**kwargs)
455456

456457
def to_internal_value(self, data):
458+
queryset = self.get_queryset()
457459
try:
458-
return self.get_queryset().get(**{self.slug_field: data})
460+
return queryset.get(**{self.slug_field: data})
459461
except ObjectDoesNotExist:
460462
self.fail('does_not_exist', slug_name=self.slug_field, value=smart_str(data))
461463
except (TypeError, ValueError):

0 commit comments

Comments
 (0)