I am receving the following error:
AttributeError: Got AttributeError when attempting to get a value for field `city` on serializer `SearchCitySerializer`
my serializers are correct though unless I am clearly missing something.
Here is my model:
class SearchCity(models.Model):
city = models.CharField(max_length=200)
here is my serializer
class SearchCitySerializer(serializers.ModelSerializer):
class Meta:
model = SearchCity
fields = ('pk','city')
*** I tried the serializer without the pk in the field and it still failed
and here it is used in the view:
from serializers import SearchCitySerializer
def get(self, request, format=None):
searchcityqueryset = SearchCity.objects.all()
serializedsearchcity = SearchCitySerializer(searchcityqueryset)
return Response({
'searchcity': serializedsearchcity.data,
})
the full error I am getting:
File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/suitsandtables/suitsandtablessettingsapp/views.py", line 37, in get
'searchcity': serializedsearchcity.data,
File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 537, in data
ret = super(Serializer, self).data
File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 491, in to_representation
attribute = field.get_attribute(instance)
File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/local/lib/python2.7/site-packages/rest_framework/fields.py", line 462, in get_attribute
raise type(exc)(msg)
AttributeError: Got AttributeError when attempting to get a value for field `city` on serializer `SearchCitySerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'city'.
[28/Feb/2018 02:41:43] "GET /api/dependancy/suitsadmin/settings/ HTTP/1.1" 500 20823
THE DATABASE IS CURRENTLY EMPTY AS IN NO DATA IN THE DATABASE AT ALL
serializedsearchcity = SearchCitySerializer(searchcityqueryset)
change to
serializedsearchcity = SearchCitySerializer(searchcityqueryset, many=True)
To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True
flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.