Ticket #6785: query-get-patch.diff
File query-get-patch.diff, 1.8 KB (added by , 17 years ago) |
---|
-
django/db/models/query.py
153 153 Performs the query and returns a single object matching the given 154 154 keyword arguments. 155 155 """ 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. 157 159 obj_list = list(clone) 158 160 if len(obj_list) < 1: 159 161 raise self.model.DoesNotExist("%s matching query does not exist." 160 162 % self.model._meta.object_name) 161 163 elif len(obj_list) > 1: 162 164 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)) 164 166 return obj_list[0] 165 167 166 168 def create(self, **kwargs): -
tests/modeltests/basic/models.py
244 244 >>> s1 & s2 245 245 [] 246 246 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) 250 Traceback (most recent call last): 251 ... 252 MultipleObjectsReturned: get() returned more than one Article -- it returned 8! Lookup parameters were {'pub_date__year': 2005} 253 247 254 # You can get the number of objects like this: 248 255 >>> len(Article.objects.filter(id__exact=1)) 249 256 1