Reputation: 561
I got this error when I'm trying to obtain data from models in my view.Thing is, I understand clearly what this error is,but I am very confused why it is happening.It is becouse when I run following code in django shell i'm getting what i want.
In django shell:
In [2]: from ep.models import *
In [3]: a = PreventionProgramCenter.objects.all()
In [4]: a.values_list('center',flat=True)
Out[4]: <QuerySet [1, 2, 3]>
In [5]: b=a[0]
In [6]: b
Out[6]: <PreventionProgramCenter: PreventionProgramCenter object (1)>
In [7]: b.center.zip_code
Out[7]: '53-334'
In [8]: for i in a:
...: print(i)
...:
PreventionProgramCenter object (1)
PreventionProgramCenter object (2)
PreventionProgramCenter object (3)
It is all good.I can get list of object from my model,iterate over it and calls methods.
But in my view.py
zip_codes = []
zip_codes_obj = PreventionProgramCenter.objects.all()
zip_codes_obj = zip_codes_obj.values_list('center',flat=True)
for zip_code in zip_codes_obj:
print(zip_code)
zip_codes.append(zip_code.center.zip_code)
zip_code
is just int,not object of PreventionProgramCenter.How,what I'm missing?
Upvotes: 0
Views: 399
Reputation: 2428
In the shell example you are not assigning the value_list
to a
otherwise you'd get the same error as in your view.
In [3]: a = PreventionProgramCenter.objects.all()
In [4]: a.values_list('center',flat=True)
Out[4]: <QuerySet [1, 2, 3]>
Here, variable a
stays PreventionProgramCenter.objects.all()
, iterable of PreventionProgramCenter
objects. While in the view code
zip_codes_obj = PreventionProgramCenter.objects.all()
zip_codes_obj = zip_codes_obj.values_list('center',flat=True)
You are assigning to zip_codes_obj
a values_list
~ list of integers.
Upvotes: 2