Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over queryset values

Tags:

python

django

I wrote a little app that allows users to create their own excel reports. One of my queries unpacks a list to .values() to return the columns. The problem I am having is trying to iterate/reference those values returned as I don't know what values are included in the report.

Here is my attempt:

queryset = Claim.objects.filter(client=client, creation__year=year, creation__month=month)\
            .values(*values).order_by('id')

for i, c in enumerate(queryset):
    for ii, r in enumerate(c):
         print c

I get

 TypeError: 'Claim' object is not iterable
like image 257
Mantis Avatar asked Jan 06 '16 13:01

Mantis


People also ask

Is a QuerySet iterable?

The QuerySet is an iterable - once we've iterated over the queryset once, the queryset puts the DB result into a cache. On every subsequent iteration, we'll use the cached objects. This prevents us from unwanted queries duplication.

What is QuerySet?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.


1 Answers

The issue is your 5th line for ii, r in enumerate(c): you CANNOT enumerate a Model type.

You CAN quit while you're ahead on the first loop. (I dont understand why the second loop is there..)

for i, c in enumerate(queryset):
    print i, c, type(c)

and you'll get something like:

0 {[some dict data]} <dict>
1 {[some dict data]} <dict>
2 {[some dict data]} <dict>
3 {[some dict data]} <dict>
....
like image 177
Javier Buzzi Avatar answered Oct 03 '22 11:10

Javier Buzzi