0

I want get the list from db and convert it to js associative arrays.

def lesson(request, block_id):
block_name = Block.objects.get(id=block_id)
item = Item.objects.filter(item_id=block_id)

item_json = json.dumps(item)

context = {
    "item_block": block_name,
    "item_json": item_json
}
return render_to_response('item_page.html', context)

In js I have

 <script>
   var counts = JSON.parse("{{ item_json }}");
   console.log(counts)
 </script>

But I have error

<QuerySet [<Item: Item object>, <Item: Item object>, <Item: Itemobject>]>

How I can get the array with objects and use it in js?

  • Check http://stackoverflow.com/questions/16790375/django-object-is-not-json-serializable. It should solve the problem. – rkatkam Apr 06 '17 at 19:50

1 Answers1

0

For serializing django queryset you must use django serializers. Your code will look like this:

from django.core import serializers

def lesson(request, block_id):
    block_name = Block.objects.get(id=block_id)
    item = Item.objects.filter(item_id=block_id)

    item_json = serializers.serialize('xml', item)

    context = {
        "item_block": block_name,
        "item_json": item_json
    }
    return render_to_response('item_page.html', context)

Note that serialized object have following format:

{
    "model": "app_name.model_name", 
    "pk": 1, 
    "fields": {"field1": 1, "field2": 2, etc..} 
}
Dima Kudosh
  • 7,126
  • 4
  • 36
  • 46