gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:04:38 26 4
gpt4 key购买 nike

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

但是在我看来我使用:

 order_items = json.dumps(order_items)

我得到:

Object of type QuerySet is not JSON serializable

View :

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

模型.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 Uncaught SyntaxError: Unexpected token & in JSON at position 0 at JSON.parse () at (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;}}]')

最佳答案

您可以使用 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 }}')

关于javascript - Django:序列化QuerySet并将其发送到模板以与Javascript一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56171422/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com