Dennis Kioko
Dennis Kioko

Reputation: 731

Serializing Django Model Instances (querysets with values tag)

I am trying to serialize the following view

def headerimage(request):

service_view = list( Service_images.objects.filter(service='7'))


return render_to_response ('headerimage.html',{'service_view':service_view}, context_instance=RequestContext(request))

This is supposed to return JSON in the form shown below

{"folderList":
    ["with schmurps"],
 "fileList":
    ["toto006.jpg",
     "toto012.jpg",
     "toto013.jpg"
    ]
}

However, The folder list can be one or in this case will be "7" given that is the title("folder") of the images.

After taking into account the answer below, I came up with

def headerimage(request):

service_view =  Service_images.objects.filter(service='7')
image = serializers.serialize("json", service_view)

mini = list(serializers.deserialize("json", image))


return HttpResponse(image, mimetype='application/javascript')

however, I am still looking for the simplest way to do this

service_view =  Service_images.objects.filter(service='7').values('image')

The problem is that the django serializer expects whole models

Upvotes: 0

Views: 1224

Answers (2)

Sunny Nanda
Sunny Nanda

Reputation: 2382

I usually follow the below way, when the json format requirement does not match with my model's representation.

from django.utils import simplejson as json

def headerimage(request):

    service_view =  Service_images.objects.filter(service='7')

    ret_dict = {
       "folderList":
          [sv.image.folder for sv in service_view],
       "fileList":
          [sv.image.file for sv in service_view]
    }
    return (json.dumps(ret_dict), mimetype="application/json")

Upvotes: 0

bx2
bx2

Reputation: 6486

Service_images.objects.filter() will return a QuerySet object for you, so basically wrapping this into list() makes no sense...

Look at the docs: http://docs.djangoproject.com/en/dev/topics/serialization/#id2, and use LazyEncoder definied there.

Upvotes: 1

Related Questions