Ticket #4373: get_blank_or_404.diff

File get_blank_or_404.diff, 2.0 KB (added by SuperJared, 17 years ago)

Diff for django/shortcuts/init.py

  • __init__.py

     
    55from django.template import loader
    66from django.http import HttpResponse, Http404
    77from django.db.models.manager import Manager
     8from django.db.models.query import QuerySet
    89
    910def render_to_response(*args, **kwargs):
    1011    return HttpResponse(loader.render_to_string(*args, **kwargs))
    1112load_and_render = render_to_response # For backwards compatibility.
    1213
     14def _get_queryset(klass):
     15    '''
     16    Returns a queryset from a Model, Manager or Queryset. Created to make
     17    get_object_or_404 and get_list_or_404 more DRY.
     18    '''
     19    if isinstance(klass, QuerySet):
     20        return klass
     21    else:
     22        if isinstance(klass, Manager):
     23            manager = klass
     24        else:
     25            manager = klass._default_manager
     26        return manager.all()
     27
    1328def get_object_or_404(klass, *args, **kwargs):
    14     if isinstance(klass, Manager):
    15         manager = klass
    16         klass = manager.model
    17     else:
    18         manager = klass._default_manager
     29    queryset = _get_queryset(klass)
    1930    try:
    20         return manager.get(*args, **kwargs)
    21     except klass.DoesNotExist:
    22         raise Http404('No %s matches the given query.' % klass._meta.object_name)
     31        return queryset.get(*args, **kwargs)
     32    except queryset.model.DoesNotExist:
     33        raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
    2334
    2435def get_list_or_404(klass, *args, **kwargs):
    25     if isinstance(klass, Manager):
    26         manager = klass
    27     else:
    28         manager = klass._default_manager
    29     obj_list = list(manager.filter(*args, **kwargs))
     36    queryset = _get_queryset(klass)
     37    obj_list = list(queryset.filter(*args, **kwargs))
    3038    if not obj_list:
    31         raise Http404('No %s matches the given query.' % manager.model._meta.object_name)
     39        raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
    3240    return obj_list
Back to Top