Rayhaan Jaufeerally
Rayhaan Jaufeerally

Reputation: 359

Django error serilaizing output of query into JSON

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

Answers (2)

Janusz
Janusz

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

Liorsion
Liorsion

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

Related Questions