Thursday, September 12, 2013

Django - generate list of individual item from queryset result

How to get particular value from Django queryset result set -

Lets say you only one field 'question_id' from Paper object -

> Paper.objects.values('question_id')
>[{'question_id': 311L}, {'question_id': 310L}, {'question_id': 291L}, {'question_id': 302L}, {'question_id': 301L}, {'question_id': 300L}, {'question_id': 299L}, {'question_id': 298L}, {'question_id': 294L}, {'question_id': 293L}, {'question_id': 282L}, {'question_id': 281L}, {'question_id': 235L}, {'question_id': 234L}, {'question_id': 233L}, {'question_id': 47L}, {'question_id': 276L}, {'question_id': 48L}]

Now if you want to make list of this question_ids, one way is to loop thru the list of dict and fetch the value, but easy way is following -

>Paper.objects.values_list('question_id', flat=True)
>[311L, 310L, 291L, 302L, 301L, 300L, 299L, 298L, 294L, 293L, 282L, 281L, 235L, 234L, 233L, 47L, 276L, 48L]

No comments:

Post a Comment