0

what is difference between two The following sentence

from django.shortcuts import get_object_or_404

and

from rest_framework.generics import get_object_or_404
Ali Rahmani
  • 37
  • 1
  • 7

1 Answers1

1

django.shortcuts.get_object_or_404 can raise errors other than Http404 (namely TypeError, ValueError, and ValidationError) in case that the type of the kwarg passed does not match the required types. Hence rest_framework.generics.get_object_or_404 is simply wrapping django.shortcuts.get_object_or_404 such that Http404 is still raised even in these cases as DRF uses the function internally and the passed data can easily fail to match the required datatypes causing unintended 500 errors.

This can be seen from DRF's source code [GitHub]:

from django.shortcuts import get_object_or_404 as _get_object_or_404


def get_object_or_404(queryset, *filter_args, **filter_kwargs):
    """
    Same as Django's standard shortcut, but make sure to also raise 404
    if the filter_kwargs don't match the required types.
    """
    try:
        return _get_object_or_404(queryset, *filter_args, **filter_kwargs)
    except (TypeError, ValueError, ValidationError):
        raise Http404
Abdul Aziz Barkat
  • 19,475
  • 3
  • 20
  • 33
  • `rest_framework.generics.get_object_or_404` should be better since you are dealing with an API and it would be more likely for wrong types, etc. to be passed to the function. (In normal views such parameters are mostly passed from the url as kwargs and normally path converters should catch incorrect types and give a 404) – Abdul Aziz Barkat Jun 17 '21 at 06:14