Django:序列化QuerySet并将其发送到模板以与Javascript一起使用

时间:2019-05-16 14:56:37

标签: javascript django

我有一个QuerySet,我需要将其发送到我的模板,因为我需要操纵其值以生成JS数组。

但是在我看来,我使用:

 order_items = json.dumps(order_items)

我得到:

Object of type QuerySet is not JSON serializable

视图:

import json

def thanks_deposit_payment(request):

    order_number = Order.objects.latest('id').id
    total = Order.objects.latest('id').total
    costo_despacho = Order.objects.latest('id').shipping_cost
    order_items = OrderItem.objects.filter(order=Order.objects.latest('id'))
    # order_items = json.dumps(order_items)

    response = render(request, 'thanks_deposit_payment.html', dict(order_number=order_number, total=total,
                                                                   order_items=order_items, costo_despacho=costo_despacho))
    return response

models.py

class OrderItem(models.Model):
    order = models.ForeignKey(Order, on_delete=models.CASCADE)
    product = models.CharField(max_length= 200)
    quantity = models.CharField(max_length= 200)
    size = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name= 'PEN Price')
    file = models.FileField(upload_to='files', blank=True, null=True)
    comment = models.CharField(max_length=200, blank=True, null=True, default='')
    uploaded_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "OrderItem"

我需要使用从后端发送的order_items中的项目生成产品数组:

 <script>
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            event: 'eec.purchase',
            ecommerce: {
                currencyCode: 'PEN',
                purchase: {
                    actionField: {
                        id: {{ order_number }},
                        affiliation: 'Stickers Gallito E-Commerce',
                        revenue: {{ total }},
                        shipping: {{ costo_despacho }},
                        coupon: 'SUMMER2019'
                    }
                },
                products: [

    {% for item in order_items %}
                  {
                    id: item.order.id,
                    name: item.product,
                    price: item.price,
                    size: item.size,
                    quantity: item.quantity
                  },
    {% endfor %}
                ]
            }
        });
    </script>

更新1:

我用ruddras回答,我在做

def thanks_deposit_payment(request):
    order_number = Order.objects.latest('id').id

    total = Order.objects.latest('id').total

    costo_despacho = Order.objects.latest('id').shipping_cost

    order_items = OrderItem.objects.filter(order=Order.objects.latest('id'))
    order_items = json.dumps(serialize('json', order_items))

    response = render(request, 'thanks_deposit_payment.html', dict(order_number=order_number, total=total,
                                                                   order_items=order_items, costo_despacho=costo_despacho))
    return response

但是出现错误:

  

VM1835:1未捕获的SyntaxError:意外的令牌和JSON中的位置   0       在JSON.parse()       在(index):55

thanks_deposit_payment.html 中:

{% block data_layer %}

<script>
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
        event: 'eec.purchase',
        ecommerce: {
            currencyCode: 'PEN',
            purchase: {
                actionField: {
                    id: {{ order_number }},
                    affiliation: 'Stickers Gallito E-Commerce',
                    revenue: {{ total }},
                    shipping: {{ costo_despacho }},
                    coupon: 'SUMMER2019'
                }
            },
            products: JSON.parse('{{ order_items }}')
        }
    });
</script>

{% endblock %}

更新2

Chrome的Web开发人员工具中的控制台选项卡:

VM2315:1 Uncaught SyntaxError: Unexpected token & in JSON at position 2
    at JSON.parse (<anonymous>)
    at (index):55

“来源”标签(第55行):

products: JSON.parse('[{&quot;model&quot;: &quot;order.orderitem&quot;, &quot;pk&quot;: 8, &quot;fields&quot;: {&quot;product&quot;: &quot;Sobre con muestras&quot;, &quot;price&quot;: &quot;3.00&quot;}}]')

2 个答案:

答案 0 :(得分:2)

您可以使用Django JSON Serializer将查询集转换为JSON字符串:

from django.core.serializers import serialize
order_items = OrderItem.objects.filter(order=Order.objects.latest('id'))
order_items = serialize('json', order_items, fields=['id', 'product', 'price'])  # the fields needed for products

然后在模板中使用它:

 products: JSON.parse('{{ order_items | safe }}')

答案 1 :(得分:0)

尝试一下:

def thanks_deposit_payment(request):
 order_number = Order.objects.latest('id').id
 total = Order.objects.latest('id').total
 costo_despacho = Order.objects.latest('id').shipping_cost
 order_items = OrderItem.objects.filter(order=Order.objects.latest('id'))

 return JSONResponse(...here goes the dict with all data to send to view)

即使您要发送所有此查询集,也可以在dict中发送一个dict。) 稍后,我建议您将AJAX与JQuery一起使用。