Reputation: 69
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
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
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