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?
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.
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.
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).
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!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With