Ticket #2482: values-flat.diff
File values-flat.diff, 3.1 KB (added by , 18 years ago) |
---|
-
django/db/models/query.py
305 305 # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS # 306 306 ################################################## 307 307 308 def values(self, *fields): 309 return self._clone(klass=ValuesQuerySet, _fields=fields) 308 def values(self, *fields, **kwds): 309 """ 310 Returns a list of dictionaries instead of object instances. Only 311 retrieves fields listed in '*fields'. If the keyword argument 'flat' 312 is True, returns a "flattened" list of field values. 313 """ 314 if kwds: 315 assert 'flat' in kwds, "only accepts keyword argument 'flat'" 316 assert kwds['flat'] in (True, False), "keyword argument 'flat' must be either True or False" 317 flat = kwds['flat'] 318 else: 319 flat = False 320 return self._clone(klass=ValuesQuerySet, _fields=fields, _flat=flat) 310 321 311 322 def dates(self, field_name, kind, order='ASC'): 312 323 """ … … 531 542 if not rows: 532 543 raise StopIteration 533 544 for row in rows: 534 yield dict(zip(field_names, row)) 545 # if self._flat is True, return a "flattened" list of 546 # field values as a plain list or a list of tuples 547 if self._flat: 548 if len(field_names) == 1: 549 yield row[0] 550 else: 551 yield tuple(row) 552 # otherwise, return a dict of field names and values 553 else: 554 yield dict(zip(field_names, row)) 535 555 536 556 def _clone(self, klass=None, **kwargs): 537 557 c = super(ValuesQuerySet, self)._clone(klass, **kwargs) 538 558 c._fields = self._fields[:] 559 c._flat = self._flat 539 560 return c 540 561 541 562 class DateQuerySet(QuerySet): -
tests/modeltests/lookup/models.py
124 124 >>> list(Article.objects.filter(id=5).values()) == [{'id': 5, 'headline': 'Article 5', 'pub_date': datetime(2005, 8, 1, 9, 0)}] 125 125 True 126 126 127 # if you specify only one field and pass the keyword argument flat=True, a 128 # plain list of field values is returned 129 >>> list(Article.objects.order_by('id').values('id', flat=True)) == [1, 2, 3, 4, 5, 6, 7] 130 True 131 132 # if you specify more than one field and pass the keyword argument flat=True, 133 # a list of tuples of field values is returned 134 >>> for t in Article.objects.order_by('id').values('id', 'headline', flat=True): 135 ... t 136 (1, 'Article 1') 137 (2, 'Article 2') 138 (3, 'Article 3') 139 (4, 'Article 4') 140 (5, 'Article 5') 141 (6, 'Article 6') 142 (7, 'Article 7') 143 127 144 # Every DateField and DateTimeField creates get_next_by_FOO() and 128 145 # get_previous_by_FOO() methods. 129 146 # In the case of identical date values, these methods will use the ID as a