猿问

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

我有一个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中的项来生成products数组:


 <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: [

Qyouu
浏览 1255回答 2
2回答

拉风的咖菲猫

您可以使用Django JSON Serializer将queryset转换为JSON String:from django.core.serializers import serializeorder_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 }}')

墨色风雨

试试这个:def thanks_deposit_payment(request):&nbsp;order_number = Order.objects.latest('id').id&nbsp;total = Order.objects.latest('id').total&nbsp;costo_despacho = Order.objects.latest('id').shipping_cost&nbsp;order_items = OrderItem.objects.filter(order=Order.objects.latest('id'))&nbsp;return JSONResponse(...here goes the dict with all data to send to view)甚至,如果你想发送所有这个查询集,你可以在dict中发送一个dict。)稍后,我建议你使用AJAX和JQuery。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答