【问题标题】:how can I retrieve a specific JSON data如何检索特定的 JSON 数据
【发布时间】:2021-08-06 15:08:56
【问题描述】:

我想在选择选项表单后检索特定数据。当我选择时,我得到了无法分离的 JSON 格式的数据。我试过 obj.purchase_price 但未定义。我的以下代码提供以下数据

           [{"model": "acc.productdetails", "pk": 4, "fields": {"purchase_price": "214.00"}}]

我想要我的表单的 purchase_price 值。请帮我分开价值。我的代码如下所示

在视图中

    def priceFilter(request):
        product_id = request.GET.get('product_id',None)

        price = {
                
             'data':serializers.serialize("json",ProductDetails.objects.filter(id=product_id),
              fields=('purchase_price',))
                }

        return JsonResponse(price) 

在我的页面中,脚本

        <script>
                $("#id_price").change(function () {
                var form = $(this).closest("form");
                $.ajax({
                 url: form.attr("data-validate-price-url"),
                 data: form.serialize(),
                 dataType: 'json',
                 success: function (price) {
                        if (price.data) {
                        let obj = price.data ;
                        alert(obj) ;

                        }
                       }
                     });

                   });
       </script>

我想在这里显示我的数据

       <input type="text" name="price" class="form-control" id="p_price" required>

【问题讨论】:

    标签: json django


    【解决方案1】:

    序列化程序返回一个 字符串,它是一个 JSON blob,而不是包含字典等的列表。

    您可以将结果包装在字典中:

    from django.shortcuts import get_object_or_404
    
    def priceFilter(request):
        product_id = request.GET.get('product_id')
        product = get_object_or_404(Product.objects.only('price'), id=product_id)
        price = {
            'price': product.price
        }
        return JsonResponse(price)

    在响应中,您可以通过以下方式检索对象:

    success: function (data) {
        if (data.price) {
            let obj = data.price;
            alert(obj) ;
        }
    }

    注意:通常最好使用get_object_or_404(…) [Django-doc], 然后直接使用.get(…) [Django-doc]。如果对象不存在, 例如,由于用户自己更改了 URL,get_object_or_404(…) 将导致返回 HTTP 404 Not Found 响应,而使用 .get(…) 将导致 HTTP 500 服务器错误

    【讨论】:

    • 如何在我的输入表单中显示价格。
    • @Shanzedul:在 JavaScript 函数中使用 success:$("#id_price").value(data.price);
    猜你喜欢
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 2023-04-05
    相关资源
    最近更新 更多