Reputation: 359
Hi I am trying to use Django to make a page that will search a database fro a certain keyword, I have managed to search the database for the keyword, but now I need to serialize the data into a JSON formatted array so I can use it on the client side using JavaScript.
When I try to serialize my result array I get this error:
'dict' object has no attribute '_meta'
My code looks like this:
def SearchItems(request, itemName):
items_list = list(Item.objects.filter(name = itemName).values())
json_serializer = serializers.get_serializer("json")()
data = json_serializer.serialize(items_list, ensure_ascii=False)
return HttpResponse(data)
Any help would be greatly appreciated, RayQuang
Upvotes: 0
Views: 827
Reputation: 1
do not convert an object to the dict. simply pass a queryset to the serializer:
json_serializer.serialize(Item.objects.filter(name=itemName), ensure_ascii=False)
alternatively, you can use json/cjson/anyjson serializer directly:
import anyjson
HttpResponse(anyjson.serialize(Item.objects.filter(name=itemName).values()), content_type="application/json")
Upvotes: 0
Reputation: 582
Instead of using serializer, trying doing this:
return HttpResponse(simplejson.dumps(items_list),'application/json'))
see this answer for more info
Upvotes: 2