avatar
avatar

Reputation: 12495

django/json - Exception Value, <model: field1 field2 ... > is not JSON serializable

I'm working on a function in the views.py that will be used for an ajax request that looks like this:

def myfunction(request):
            ...
            p = M1.objects.filter(user=request.user)            
            n = M2.objects.filter(myrecord=p)           
            results["res1"] = list(p)
            results["res2"] =  list(q)

    return HttpResponse(json.dumps(results), mimetype='application/javascript')

When I call myfunction using ajax I get an error like this:

Exception Value:

<M1: test1 test1 2011-06-17 2011-06-17> is not JSON serializable

Any ideas how to fix it?

Upvotes: 0

Views: 715

Answers (1)

Zach Kelling
Zach Kelling

Reputation: 53819

That's because the json module only serializes native data types by default, you have to tell it how to serialize arbitrary objects. Django has built-in support for serializing querysets and objects, or you can write your own serializer:

from django.core import serializers
json_serializer = serializers.get_serializer("json")()
json_serializer.serialize(queryset)

Upvotes: 4

Related Questions