djangodjango-rest-frameworkdrf-queryset

difference between django.shortcuts and rest_framework.generics


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

Solution

  • 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