Retrieving row tuples / dictionaries / namedtuples
Sometimes you do not need the overhead of creating model instances and simplywant to iterate over the row data without needing all the APIs providedModel
. To do this, use:
dicts()
namedtuples()
tuples()
objects()
– accepts an arbitrary constructor functionwhich is called with the row tuple.
- stats = (Stat
- .select(Stat.url, fn.Count(Stat.url))
- .group_by(Stat.url)
- .tuples())
- # iterate over a list of 2-tuples containing the url and count
- for stat_url, stat_count in stats:
- print(stat_url, stat_count)
Similarly, you can return the rows from the cursor as dictionaries usingdicts()
:
- stats = (Stat
- .select(Stat.url, fn.Count(Stat.url).alias('ct'))
- .group_by(Stat.url)
- .dicts())
- # iterate over a list of 2-tuples containing the url and count
- for stat in stats:
- print(stat['url'], stat['ct'])