简体   繁体   English

如何 JSON 解析 Django 查询集?

[英]How do I JSON parse a Django queryset?

So I'm trying to parse each object in my Django queryset, and deal with the data through JavaScript.所以我试图解析我的 Django 查询集中的每个对象,并通过 JavaScript 处理数据。 Below is my code (simplified) :下面是我的代码(简化):
views.py (using Django Paginator, but the basic idea is the same.) views.py(使用 Django Paginator,但基本思想是一样的。)

def main_page(request):
    all_contents = Contents.objects.all()
    paginator_contents = Paginator(contents,10)
    page = request.GET.get('page')
    all_contents_paginated = paginator_contents.get_page(page)

    context = {
            'contents' : contents,
            'all_contents_paginated' : all_contents_paginated
        }

    return render(request, 'main/home.html', context)

template模板

{% for c in all_contents_paginated %}
<div class="text-m">
    {{c.author}}
</div>
<div class="text-s" onclick="DetailModal('{{c}}')">
    {{c.body}}
</div>
{% endfor %}

<script>
    function DetailModal(c) {

    }
</script>

Now obviously, the '{{c}}' cannot be parsed into JSON since it's string.现在很明显, '{{c}}'不能解析为 JSON,因为它是字符串。 I want to parse it into JSON in function DetailModal() and display the data in a separate modal element or do any other stuff with each data.我想在function DetailModal()中将其解析为 JSON 并在单独的模态元素中显示数据或对每个数据执行任何其他操作。 But I can't figure out how to parse each object in the Django queryset.但我不知道如何解析 Django 查询集中的每个对象。

Any ideas?有任何想法吗? Thanks.谢谢。

you just modify your script to parse your item:你只需修改你的脚本来解析你的项目:

<script>
    function DetailModal(c) {
       const obj = JSON.parse(c);
       console.log(obj.author);   
       console.log(obj.body);
    }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM