[Fixed]-Django object is not iterable using serializers.serialize

27👍

That’s because you’re not passing an iterable nor a QuerySet, you’re passing instead a Template object. If you want to serialize that single object you can do it like this:

def get_AJAX(request, id):
    data = serializers.serialize("json", [Template.objects.get(pk=id)])
    return HttpResponse(data)

UPDATE: Recommending using filter instead.

Also consider using filter instead of get in order to avoid possible exceptions if pk doesn’t exists. This way you don’t need the brackets because it is a QuerySet object

def get_AJAX(request, id):
    data = serializers.serialize("json", Template.objects.filter(pk=id))
    return HttpResponse(data)

Hope it helps!

1👍

Following Paulo Bu Example. Sometimes we’d like to use get due it offers other functionalities like get_object_or_404(), this function uses get under the hood, so a little workaround is to enclosed the object in a list.

def get_AJAX(request, id):
    _data = [Template.objects.get(pk=id)] # This is now list.
    data = serializers.serialize("json", _data)
    return HttpResponse(data)

or

def get_AJAX(request, id):
    _data = [get_object_or_404(Template, pk=id)] # This is now list.
    data = serializers.serialize("json", _data)
    return HttpResponse(data)

0👍

If you want to return an Object without it being in a List, just simply do this :

serializer = CustomSerializerClass(queryset) # This queryset is the one with a get()

return Response(status=status.HTTP_201_CREATED, data=serializer.data)

Note :

You don’t need to add many=True in the serializer :

serializer = CustomSerializerClass(queryset)

Leave a comment