11

I have a database which has records with several fields containing some info.

To get all the data in the table matching some filter I'd do this:

records = Record.objects.filter(fieldA='a')

records, I suppose, is a QuerySet object and contains a "list" of records. Is that correct?

Now let's say I want a list of the values in one field.

If I do this:

records = Record.objects.filter(fieldA='a').only('fieldB')

I still get a queryset, but now it has some deferred fields. What I want is just a list of the values I meant to grab aka fieldB. I also want to be able to grab the distinct values of fieldB. I suppose I could just iterate over each record, pull out fieldB, add it to a list if it's not already there, and there it is, but there's gotta be a better way.

Thanks!

EDIT: I think what I'm looking for is

Record.objects.values_list('fieldB')
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
JPC
  • 8,096
  • 22
  • 77
  • 110

2 Answers2

12

Yup, found it: values_list. Here's the reference: https://docs.djangoproject.com/en/dev/ref/models/querysets/#values-list

D Malan
  • 10,272
  • 3
  • 25
  • 50
JPC
  • 8,096
  • 22
  • 77
  • 110
  • 7
    That produces a list of 1-value tuples `(('a',), ('b',), ('c',))`, which probably isn't what you want. If you pass flat=True to values_list (`Record.objects.values_list('fieldB', flat=True)`) you'll get a flat list `('a', 'b', 'c')`. – James S Mar 27 '14 at 09:34
9

I am posting the comment by James here to make it more prominent. It was certainly what I was looking for.

I wanted a list of values. Using the QuerySet method .values_list() returned a list of tuples. To get a list of values, I needed the option flat=True.

Record.objects.values_list('fieldB', flat=True) 
D Malan
  • 10,272
  • 3
  • 25
  • 50
Joshua Cook
  • 12,495
  • 2
  • 35
  • 31