由于Google增强型电子商务需要如何处理数据,我需要将OrderItem对象的字段product
更改为name
。
Google Analytics(分析)电子商务的必填字段:
工作示例
https://developers.google.com/tag-manager/enhanced-ecommerce#purchases
如前所述,我的模型将此字段命名为product
,但Google需要将其命名为name
是否可以在视图中更改它?还是我需要改变它 使用Javascript以某种方式在HTML中实现?
视图
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 = serialize('json', order_items, fields=['id', 'sku', 'product', 'price', 'size', 'quantity'])
response = render(request, 'thanks_deposit_payment.html', dict(order_number=order_number, total=total,
order_items=order_items, costo_despacho=costo_despacho))
return response
模板:
<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: ''
},
products: JSON.parse('{{ order_items | safe }}')
},
}
});
</script>
models.py
class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
product = models.CharField(max_length= 200)
sku = models.CharField(max_length=20)
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)
更新1
感谢ruddra回答,我将'产品'更改为'名称',但dataLayer显示:
Uncaught SyntaxError: missing ) after argument list
products: JSON.parse('[{'sku': 'M1', 'quantity': '10', 'size': 'varios', 'price': '3.00', 'name': 'Sobre con muestras'}]')
只有当我用答案中的建议改变看法时,这种情况才会发生。
答案 0 :(得分:2)
您可以注释查询集,以便结果具有一个name
字段
q = Q(order=Order.objects.latest('id'))
order_items = OrderItem.objects.filter(q).annotate(name=F('product'))
然后在序列化器字段中将product
替换为name
。
编辑:感谢评论者指出,这实际上是行不通的,因为Django的serialize
仅会序列化属于模型字段的属性。您还必须编写一个自定义的序列化器。
答案 1 :(得分:1)
可以更改视图,您可以这样做:
order_items = serialize('json', order_items, fields=['id', 'product', 'price']) # the fields needed for products
order_items_json = json.loads(order_items)
products_list = []
for item in order_items_json:
product_dict = item.get('fields')
product_dict['name'] = product_dict.pop('product')
products_list.append(product_dict)
return render('template_name.html', dict(order_number=order_number, total=total, order_items=json.dumps(products_list), costo_despacho=costo_despacho))