Med
Med

Reputation: 69

Cannot iterate a queryset in Django

I have this model

class AgeRange(models.Model):
    frm = models.CharField(max_length=20, blank=False)
    to = models.CharField(max_length=20, blank=False)

Now, when I try to fill a dropdown list by values contracted from frm+to fileds. So, I run this queryset:

class ReportForm(forms.ModelForm):
    ranges = AgeRange.objects.all().values()
    print(ranges)
    for item in ranges:
        print(item.frm)

It prints ranges as following:

<QuerySet [{'id': 2, 'frm': '1', 'to': '18'} ..... so on.

Then, I get this error :

print(item.frm)
AttributeError: 'dict' object has no attribute 'frm'

I'm confused why it could not recogniez "frm" when I try to iterate the queryset :

for item in ranges:
    print(item.frm)

Upvotes: 0

Views: 47

Answers (2)

S.D.
S.D.

Reputation: 2941

It's because you converted your queryset to a list of dictionaries.

Either do:

class ReportForm(forms.ModelForm):
    ranges = AgeRange.objects.all().values()
    print(ranges)
    for item in ranges:
        print(item['frm'])

or

class ReportForm(forms.ModelForm):
    ranges = AgeRange.objects.all()
    print(ranges)
    for item in ranges:
        print(item.frm)

Upvotes: 1

Pruthvi Barot
Pruthvi Barot

Reputation: 2018

you should remove values if you want all attributes in queryset. Because values() return a dictionary of field values which is passed as arguments

ranges = AgeRange.objects.all()
print(ranges)
for item in ranges:
    print ( item.frm)

try this way you can get frm

Upvotes: 1

Related Questions