hcsaral
hcsaral

Reputation: 63

Why cannot iterate over Model.objects.all()?

In Django shell I don't have any problems in looping over Airport.objects.all() but in a .py I cannot iterate over my model's QuerySet. Here is my code:

from django.forms import ModelForm,DateField,ChoiceField
from flights.models import Flight,Airport
from django.forms.widgets import SelectDateWidget,TextInput
from datetime import datetime

# pylint: disable=no-member
queries=Airport.objects.all()
airports = [tuple(x) for x in queries]

I got TypeError: 'Airport' object is not iterable. Why?

Upvotes: 0

Views: 2334

Answers (1)

Siva Sankar
Siva Sankar

Reputation: 1830

queries=Airport.objects.all()
airports = [tuple(x) for x in queries]

Let's break this code:

we can write this line:

airports = [tuple(x) for x in queries]

as

airports = []
for x in queries:
    airports.append((x))

queries is a query set. x contains django queryset object for each time loop runs. We can't directly convert django queryset object to tuple. Instead we can convert the attributes (model field names) of that object in to a tuple like this:

airports = [tuple(x.id) for x in queries] # [(1,), (2,)])

or

airports = [tuple(x.name) for x in queries] # [('airport1',), ('airport2',)]
    

Django value_list provides the same result as above:

enter image description here

Note: Img source - Django documentation

Upvotes: 2

Related Questions