Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django object is not iterable using serializers.serialize

Tags:

django

I'm getting the following error,

Template' object is not iterable

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

However, I'm using 'get' so I don't understand why I'm getting this error. Any ideas?

like image 871
GrantU Avatar asked May 19 '13 22:05

GrantU


People also ask

Is serialization necessary in Django?

It is not necessary to use a serializer. You can do what you would like to achieve in a view. However, serializers help you a lot. If you don't want to use serializer, you can inherit APIView at a function-based-view.

Why serializers are used in Django?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

What is serializing in Django?

Django's serialization framework provides a mechanism for “translating” Django models into other formats. Usually these other formats will be text-based and used for sending Django data over a wire, but it's possible for a serializer to handle any format (text-based or not).


2 Answers

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!

like image 60
Paulo Bu Avatar answered Oct 11 '22 12:10

Paulo Bu


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)
like image 28
Wolfgang Leon Avatar answered Oct 11 '22 12:10

Wolfgang Leon