1

I want to loop over a queryset and access the the field values in javascript.

I'm sending the queryset from the view to the template:

render(request, 'home.html', {'data': queryset})

Now I want to access some of the fields in javascript. This cannot happen with data since it is not yet serialized.

I have no option but to get a serialized version of the queryset with the concerned fields...

userData = UserDetails.objects.all().values("first_name", "email")
from django.core import serializers
data2 = serializers.serialize('json', userData)

...but I am getting following error:

AttributeError: 'str' object has no attribute '_meta'

I tried the solution given here Serializing data results from query with select_related into json but in the javascript I get the following data:

"[{"first_name": "pream"}, {"first_name": "micel"}, {"first_name": "Johhy"}, {"first_name": "hraper"}]"

Any direction to resolve the issue will be appreciated.

Community
  • 1
  • 1
navyad
  • 3,752
  • 7
  • 47
  • 88

1 Answers1

5

I have a solution:

Use the same serialization in the views file, add in the template context and pass it to the template.

data2 = serializers.serialize('json', userData)
context = { 
        'data2' : data2,
}
return HttpResponse(template.render(context, request))

From your template get this json from the context as below and will be serialized with '"' and not 'quot;'.

The scapejs instruction will do the work

var jsonData = "{{ data2|escapejs }}";

It worked for me.

Regards

Marc Sánchez
  • 66
  • 1
  • 2