Retrieving row tuples / dictionaries / namedtuples
Sometimes you do not need the overhead of creating model instances and simply want to iterate over the row data without needing all the APIs provided Model
. To do this, use:
dicts()
namedtuples()
tuples()
objects()
– accepts an arbitrary constructor function which 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 using dicts()
:
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'])