Ticket #5741: 5741.diff

File 5741.diff, 2.3 KB (added by Dan Watson, 10 years ago)

updated patch against r8194

  • django/db/models/query.py

    293293        Performs the query and returns a single object matching the given
    294294        keyword arguments.
    295295        """
     296        has_default = False
     297        if 'default' in kwargs:
     298            default_value = kwargs.pop('default')
     299            has_default = True
    296300        clone = self.filter(*args, **kwargs)
    297301        num = len(clone)
    298302        if num == 1:
    299303            return clone._result_cache[0]
    300304        if not num:
     305            if has_default:
     306                return default_value
    301307            raise self.model.DoesNotExist("%s matching query does not exist."
    302308                    % self.model._meta.object_name)
    303309        raise self.model.MultipleObjectsReturned("get() returned more than one %s -- it returned %s! Lookup parameters were %s"
  • tests/modeltests/basic/models.py

    100100    ...
    101101DoesNotExist: Article matching query does not exist.
     103# You can specify a default keyword argument to get()
     104>>> Article.objects.get(pk=97, default=False)
    103107# Lookup by a primary key is the most common case, so Django provides a
    104108# shortcut for primary-key exact lookups.
    105109# The following is identical to articles.get(id=1).
  • docs/db-api.txt

    11101110    except ObjectDoesNotExist:
    11111111        print "Either the entry or blog doesn't exist."
     1113**New in Django development version**
     1115``get()`` may take a keyword argument named ``default``, similar to the ``get()``
     1116method of a python dictionary. When ``default`` is specified and no object is
     1117found, the value of ``default`` is returned. If ``default`` is not specified, the
     1118``DoesNotExist`` exception is raised as usual.
     1120For models with a field named ``default``, the more verbose ``default__exact``
     1121lookup syntax must be used.
Back to Top