Ticket #5741: get_default.diff

File get_default.diff, 1.9 KB (added by Dan Watson, 17 years ago)
  • django/db/models/query.py

     
    254254
    255255    def get(self, *args, **kwargs):
    256256        "Performs the SELECT and returns a single object matching the given keyword arguments."
     257        has_default = False
     258        if 'default' in kwargs:
     259            default_value = kwargs.pop('default')
     260            has_default = True
    257261        clone = self.filter(*args, **kwargs)
    258262        # clean up SQL by removing unneeded ORDER BY
    259263        if not clone._order_by:
    260264            clone._order_by = ()
    261265        obj_list = list(clone)
    262266        if len(obj_list) < 1:
     267            if has_default:
     268                return default_value
    263269            raise self.model.DoesNotExist, "%s matching query does not exist." % self.model._meta.object_name
    264270        assert len(obj_list) == 1, "get() returned more than one %s -- it returned %s! Lookup parameters were %s" % (self.model._meta.object_name, len(obj_list), kwargs)
    265271        return obj_list[0]
  • docs/db-api.txt

     
    839839    except ObjectDoesNotExist:
    840840        print "Either the entry or blog doesn't exist."
    841841
     842**New in Django development version**
     843
     844``get()`` may take a kwarg named ``default``, similar to the ``get()`` method
     845on dicts. When ``default`` is specified, and no object is found, the value of
     846``default`` is returned. If ``default`` is not specified, the ``DoesNotExist``
     847exception is raised as usual.
     848
     849For existing models with a field named ``default``, the more verbose
     850``default__exact`` lookup syntax must be used.
     851
    842852``create(**kwargs)``
    843853~~~~~~~~~~~~~~~~~~~~
    844854
Back to Top