Passing objects from Django to Javascript DOM

前端 未结 14 1150
野的像风
野的像风 2020-12-04 21:26

I\'m trying to pass a Query Set from Django to a template with javascript.

I\'ve tried different approaches to solve this:

1. Normal Approach - Javas

14条回答
  •  盖世英雄少女心
    2020-12-04 21:58

    Your problem is that, as so often, your requirements are under-specified. What exactly do you want the JSON to look like? You say you want to "serialize the queryset", but in what format? Do you want all the fields from each model instance, a selection, or just the unicode representation? When you've answered that question, you'll know how to solve your problem.

    One approach, for example, might be to use the values queryset method to output a dictionary of fields for each instance, and serialize that (you need to convert it to a list first):

    data = SomeObject.objects.values('field1', 'field2', 'field3')
    serialized_data = simplejson.dumps(list(data))
    

提交回复
热议问题