Passing objects from Django to Javascript DOM

前端 未结 14 1128
野的像风
野的像风 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 22:12

    Same Question, "Better"(more recent) answer: Django Queryset to dict for use in json

    Answer by vashishtha-jogi:

    A better approach is to use DjangoJSONEncoder. It has support for Decimal.

    import json
    from django.core.serializers.json import DjangoJSONEncoder
    
    prices = Price.objects.filter(product=product).values_list('price','valid_from')
    
    prices_json = json.dumps(list(prices), cls=DjangoJSONEncoder)
    

    Very easy to use. No jumping through hoops for converting individual fields to float.

    Update : Changed the answer to use builtin json instead of simplejson.

    This is answer came up so often in my google searches and has so many views, that it seems like a good idea to update it and save anyone else from digging through SO. Assumes Django 1.5.

提交回复
热议问题