Reputation: 25
I'm pretty new to Django. I'm trying to iterate over my queryset and add the field which happens to be called 'id' of each to a new list.
My end result should be a list looking something like this (for example): [1, 2, 3, 7, 10]
My code looks like this:
my_list = []
for foo in bar:
number = foo.id
my_list += number
I'm getting this error: TypeError: 'long' object is not iterable
The type of foo.id is long
I have tried changing the foo.id to an int or str using:
number = str(number)
Have also tried the solution here (I'm using Python 2.7): TypeError: 'long' object is not iterable but I get this: AttributeError: 'QuerySet' object has no attribute 'iteritems'
Any help much appreciated!
Upvotes: 1
Views: 4825
Reputation: 77902
As for why your code raises an error: you'd have to use my_list.append(number)
(my_list += anything
is a shortcut for my_list.extends(anything)
which expects an iterable and will append all values from this iterable to my_list
).
Now actually, the pythonic way here would be to use a list comprehension instead, ie :
my_list = [foo.id for foo in bar]
But since it's about a Django queryset, the right solution is to use QuerySet.values_list()
:
bar = MyModel.objects.values_list("id", flat=True)
which will result in bar
being an iterable over your queryset's 'id' values. And if you really need a list, then you just have to pass bar
to the list
constructor:
my_list = list(bar)
Upvotes: 5
Reputation: 430
It is bad practice to iterate over queryset to get id of each object. I suggest to use values_list() like. which will give you list of id of each object in queryset.
ids = bar.values_list('id', flat=True)
Upvotes: 0