Ticket #11352: object_list_404-3.diff

File object_list_404-3.diff, 9.1 KB (added by Chuck Harmston, 15 years ago)

Adds tests and documentation

  • django/shortcuts/__init__.py

     
    8989    except queryset.model.DoesNotExist:
    9090        raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
    9191
     92def get_object_or_none(klass, *args, **kwargs):
     93    """
     94    Uses get() to return an object, or returns an empty QuerySet if the list is empty.
     95
     96    klass may be a Model, Manager, or QuerySet object. All other passed
     97    arguments and keyword arguments are used in the get() query.
     98
     99    Note: Like with get(), an MultipleObjectsReturned will be raised if more than one
     100    object is found.
     101    """
     102    queryset = _get_queryset(klass)
     103    try:
     104        return queryset.get(*args, **kwargs)
     105    except queryset.model.DoesNotExist:
     106        return queryset.none()
     107
    92108def get_list_or_404(klass, *args, **kwargs):
    93109    """
    94110    Uses filter() to return a list of objects, or raise a Http404 exception if
     
    101117    obj_list = list(queryset.filter(*args, **kwargs))
    102118    if not obj_list:
    103119        raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
     120    return obj_list
     121
     122def get_list_or_none(klass, *args, **kwargs):
     123    """
     124    Uses filter() to return a list of objects, or return an empty QuerySet if
     125    the list is empty.
     126
     127    klass may be a Model, Manager, or QuerySet object. All other passed
     128    arguments and keyword arguments are used in the filter() query.
     129    """
     130    queryset = _get_queryset(klass)
     131    obj_list = list(queryset.filter(*args, **kwargs))
     132    if not obj_list:
     133        return list(queryset.none())
    104134    return obj_list
     135 No newline at end of file
  • tests/modeltests/get_object_or_404/models.py

     
    55performing a ``get()`` lookup and raising a ``Http404`` exception if a
    66``DoesNotExist`` exception was raised during the ``get()`` call.
    77
     8``get_object_or_none()`` is a shortcut function to be used in view functions for
     9performing a ``get()`` lookup and returning an empty QuerySet if a
     10``DoesNotExist`` exception was raised during the ``get()`` call.
     11
    812``get_list_or_404()`` is a shortcut function to be used in view functions for
    913performing a ``filter()`` lookup and raising a ``Http404`` exception if a
    1014``DoesNotExist`` exception was raised during the ``filter()`` call.
     15
     16``get_list_or_none()`` is a shortcut function to be used in view functions for
     17performing a ``filter()`` lookup and returning an empty QuerySet if a
     18``DoesNotExist`` exception was raised during the ``filter()`` call.
    1119"""
    1220
    1321from django.db import models
    1422from django.http import Http404
    15 from django.shortcuts import get_object_or_404, get_list_or_404
     23from django.shortcuts import get_object_or_404, get_list_or_404, \
     24                             get_object_or_none, get_list_or_none
    1625
    1726class Author(models.Model):
    1827    name = models.CharField(max_length=50)
     
    4554Traceback (most recent call last):
    4655...
    4756Http404: No Article matches the given query.
     57>>> get_object_or_none(Article, title="Foo")
     58[]
    4859
    4960# Create an Article.
    5061>>> article = Article.objects.create(title="Run away!")
     
    5465# get_object_or_404 can be passed a Model to query.
    5566>>> get_object_or_404(Article, title__contains="Run")
    5667<Article: Run away!>
     68>>> get_object_or_none(Article, title__contains="Run")
     69<Article: Run away!>
    5770
    5871# We can also use the Article manager through an Author object.
    5972>>> get_object_or_404(a.article_set, title__contains="Run")
    6073<Article: Run away!>
     74>>> get_object_or_none(a.article_set, title__contains="Run")
     75<Article: Run away!>
    6176
    6277# No articles containing "Camelot".  This should raise a Http404 error.
    6378>>> get_object_or_404(a.article_set, title__contains="Camelot")
    6479Traceback (most recent call last):
    6580...
    6681Http404: No Article matches the given query.
     82>>> get_object_or_none(a.article_set, title__contains="Camelot")
     83[]
    6784
    6885# Custom managers can be used too.
    6986>>> get_object_or_404(Article.by_a_sir, title="Run away!")
    7087<Article: Run away!>
     88>>> get_object_or_none(Article.by_a_sir, title="Run away!")
     89<Article: Run away!>
    7190
    7291# QuerySets can be used too.
    7392>>> get_object_or_404(Article.objects.all(), title__contains="Run")
    7493<Article: Run away!>
     94>>> get_object_or_none(Article.objects.all(), title__contains="Run")
     95<Article: Run away!>
    7596
    7697# Just as when using a get() lookup, you will get an error if more than one
    7798# object is returned.
     
    79100Traceback (most recent call last):
    80101...
    81102MultipleObjectsReturned: get() returned more than one Author -- it returned ...! Lookup parameters were {}
     103>>> get_object_or_none(Author.objects.all())
     104Traceback (most recent call last):
     105...
     106MultipleObjectsReturned: get() returned more than one Author -- it returned ...! Lookup parameters were {}
    82107
    83108# Using an EmptyQuerySet raises a Http404 error.
    84109>>> get_object_or_404(Article.objects.none(), title__contains="Run")
    85110Traceback (most recent call last):
    86111...
    87112Http404: No Article matches the given query.
     113>>> get_object_or_none(Article.objects.none(), title__contains="Run")
     114[]
    88115
    89116# get_list_or_404 can be used to get lists of objects
    90117>>> get_list_or_404(a.article_set, title__icontains='Run')
    91118[<Article: Run away!>]
     119>>> get_list_or_none(a.article_set, title__icontains='Run')
     120[<Article: Run away!>]
    92121
    93122# Http404 is returned if the list is empty.
    94123>>> get_list_or_404(a.article_set, title__icontains='Shrubbery')
    95124Traceback (most recent call last):
    96125...
    97126Http404: No Article matches the given query.
     127>>> get_list_or_none(a.article_set, title__icontains='Shrubbery')
     128[]
    98129
    99130# Custom managers can be used too.
    100131>>> get_list_or_404(Article.by_a_sir, title__icontains="Run")
    101132[<Article: Run away!>]
     133>>> get_list_or_none(Article.by_a_sir, title__icontains="Run")
     134[<Article: Run away!>]
    102135
    103136# QuerySets can be used too.
    104137>>> get_list_or_404(Article.objects.all(), title__icontains="Run")
    105138[<Article: Run away!>]
     139>>> get_list_or_none(Article.objects.all(), title__icontains="Run")
     140[<Article: Run away!>]
    106141
    107142"""}
  • docs/topics/http/shortcuts.txt

     
    189189Note: As with ``get()``, an ``MultipleObjectsReturned`` exception will be
    190190raised if more than one object is found.
    191191
     192``get_object_or_none``
     193=====================
     194
     195.. function:: get_object_or_none(klass, *args, **kwargs)
     196
     197   Calls :meth:`~django.db.models.QuerySet.get()` on a given model manager,
     198   but it returns an empty QuerySet rather than raising the model's
     199   ``DoesNotExist`` exception.
     200
     201Required arguments
     202------------------
     203
     204``klass``
     205    A ``Model``, ``Manager`` or ``QuerySet`` instance from which to get the
     206    object.
     207
     208``**kwargs``
     209    Lookup parameters, which should be in the format accepted by ``get()`` and
     210    ``filter()``.
     211
     212Example
     213-------
     214
     215The following example gets the object with the primary key of 1 from
     216``MyModel``::
     217
     218    from django.shortcuts import get_object_or_none
     219
     220    def my_view(request):
     221        my_object = get_object_or_none(MyModel, pk=1)
     222
     223This example is equivalent to::
     224
     225    def my_view(request):
     226        try:
     227            my_object = MyModel.objects.get(pk=1)
     228        except MyModel.DoesNotExist:
     229            my_object = MyModel.objects.none()
     230
     231Note: As with ``get()``, an ``MultipleObjectsReturned`` exception will be
     232raised if more than one object is found.
     233
    192234``get_list_or_404``
    193235===================
    194236
     
    227269        my_objects = list(MyModel.objects.filter(published=True))
    228270        if not my_objects:
    229271            raise Http404
     272
     273``get_list_or_none``
     274===================
     275
     276.. function:: get_list_or_none(klass, *args, **kwargs)
     277
     278   Returns the result of :meth:`~django.db.models.QuerySet.filter()` on a
     279   given model manager or an empty QuerySet if the resulting list is empty.
     280
     281Required arguments
     282------------------
     283
     284``klass``
     285    A ``Model``, ``Manager`` or ``QuerySet`` instance from which to get the
     286    object.
     287
     288``**kwargs``
     289    Lookup parameters, which should be in the format accepted by ``get()`` and
     290    ``filter()``.
     291
     292Example
     293-------
     294
     295The following example gets all published objects from ``MyModel``::
     296
     297    from django.shortcuts import get_list_or_none
     298
     299    def my_view(request):
     300        my_objects = get_list_or_none(MyModel, published=True)
     301
     302This example is equivalent to::
     303
     304    def my_view(request):
     305        my_objects = list(MyModel.objects.filter(published=True))
     306        if not my_objects:
     307            my_objects = list(MyModel.objects.none())
  • AUTHORS

     
    204204    Scot Hacker <shacker@birdhouse.org>
    205205    dAniel hAhler
    206206    hambaloney
     207    Chuck Harmston <chuck@chuckharmston.com>
    207208    Brian Harring <ferringb@gmail.com>
    208209    Brant Harris
    209210    Ronny Haryanto <http://ronny.haryan.to/>
Back to Top