Ticket #6785: query-get-patch.diff

File query-get-patch.diff, 1.8 KB (added by Brantley, 17 years ago)

QuerySet.get() nit-pick / optimize

  • django/db/models/query.py

     
    153153        Performs the query and returns a single object matching the given
    154154        keyword arguments.
    155155        """
    156         clone = self.filter(*args, **kwargs)
     156        filtered = self.filter(*args, **kwargs)
     157        clone = filtered._clone()
     158        clone.query.set_limits(0, 2)             # We only need at most 2.
    157159        obj_list = list(clone)
    158160        if len(obj_list) < 1:
    159161            raise self.model.DoesNotExist("%s matching query does not exist."
    160162                    % self.model._meta.object_name)
    161163        elif len(obj_list) > 1:
    162164            raise self.model.MultipleObjectsReturned("get() returned more than one %s -- it returned %s! Lookup parameters were %s"
    163                     % (self.model._meta.object_name, len(obj_list), kwargs))
     165                    % (self.model._meta.object_name, filtered.count(), kwargs))
    164166        return obj_list[0]
    165167
    166168    def create(self, **kwargs):
  • tests/modeltests/basic/models.py

     
    244244>>> s1 & s2
    245245[]
    246246
     247# Django raises an Article.MultipleObjectsReturned exception for get() if the
     248# parameters match more than one article.
     249>>> Article.objects.get(pub_date__year=2005)
     250Traceback (most recent call last):
     251    ...
     252MultipleObjectsReturned: get() returned more than one Article -- it returned 8! Lookup parameters were {'pub_date__year': 2005}
     253
    247254# You can get the number of objects like this:
    248255>>> len(Article.objects.filter(id__exact=1))
    2492561
Back to Top