Ticket #4373: get_blank_or_404.diff
File get_blank_or_404.diff, 2.0 KB (added by , 17 years ago) |
---|
-
__init__.py
5 5 from django.template import loader 6 6 from django.http import HttpResponse, Http404 7 7 from django.db.models.manager import Manager 8 from django.db.models.query import QuerySet 8 9 9 10 def render_to_response(*args, **kwargs): 10 11 return HttpResponse(loader.render_to_string(*args, **kwargs)) 11 12 load_and_render = render_to_response # For backwards compatibility. 12 13 14 def _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 13 28 def 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) 19 30 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) 23 34 24 35 def 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)) 30 38 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) 32 40 return obj_list