gadss
gadss

Reputation: 22489

QuerySet : TypeError

I have this code:

>>> d = HotelCheck.objects.filter(client=1,date_booked='2012-02-27').distinct('product').values('product')['product_id']
>>> d
[{'product': 6}, {'product': 1}]

And I just want the output to be 1 and 6.

So I tried this:

>>> d = HotelCheck.objects.filter(client=1,date_booked='2012-02-27').distinct('product').values('product')['product_id']

But I got this error:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 153, in __getitem__
    raise TypeError
TypeError

Does anyone have any ideas on how I can show only the values (6 and 1,) of the product?

Upvotes: 0

Views: 825

Answers (3)

You're looking for values_list. Pass it the flat argument, and you'll directly get a list of product ids. Your lookup is failing because ValuesQuerySet can only be sliced or integer indexed.

MyModel.objects.values_list('product', flat=True)
# Out: [6, 1]  # this is a ValuesQuerySet that behaves like a list

Upvotes: 4

tsm
tsm

Reputation: 3658

You're getting back a list of dictionaries, not a dictionary itself. So you need to iterate through them to accumulate what you need--thus John Zwinck's code.

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249153

[x['product'] for x in d]

Should give [6, 1].

Upvotes: 1

Related Questions