“dict"对象没有属性“order_by"django [英] 'dict' object has no attribute 'order_by' django
问题描述
我想返回一个 ManyToMany
字段数据,并且我已经使用了聚合进行了一些计算,现在我还需要返回产品
i want to return a ManyToMany
fields data , and also i've used aggregate to some calculation , now i need to return products as well
这是我的models.py
this is my models.py
class CustomerInvoice(models.Model):
customer = models.CharField(max_length=50)
items = models.ManyToManyField(Product,through='ProductSelecte')
date = models.DateTimeField(auto_now_add=True)
class ProductSelecte(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
products= models.ForeignKey(CustomerInvoice,on_delete=models.CASCADE,related_name='product')
qnt= models.IntegerField(default=1)
price = models.IntegerField()
cash = models.IntegerField()
这是我的查询
context['clients'] = CustomerInvoice.objects.filter(
customer=self.object.name).aggregate(
total_order=Sum(F('product__qnt')),
total_price=Sum(F('product__price')))
我想制作表格来跟踪客户活动:例如,在 6 月 4 日,他买了两支钢笔和 3 本书,而在 7 月 5 日,他买了 1 支钢笔和 2 本抄写本,我需要这样的结果:3;pen , 3;book ,2;copybook
i want to make table to track customers activity : for example at 4th june he bought two pen with 3 book , and for 5th july he buy 1 pen with 2 copybook , i need a result like this : 3; pen , 3;book ,2;copybook
我知道我应该使用 distinct
但我不知道为什么没有任何输出 {{clients.items.all|join:','}}
?感谢您的帮助
i know i should use distinct
and i dont know why dont have any output {{clients.items.all|join:','}}
?
thanks for your helping
更新
现在我将查询更改为此
context['clients'] = ProductSelecte.objects.filter(
products__customer=self.object.name).values('product').annotate(quantity=Sum(F('qnt'))).order_by('product')
直到这里工作正常,但我还需要使用它来汇总价格
till here works fine but i also need to aggregate price using this
.aggregate(
total_price=Sum(F('price')))
它引发了这个错误
'dict' 对象没有属性 'order_by'
'dict' object has no attribute 'order_by'
推荐答案
翻转你的方法.不要从 CustomerInvoice 到 ProductSelecte,而是从 ProductSelecte 到 CustomerInvoice
Flip your approach. Instead of going from CustomerInvoice to ProductSelecte, do it from ProductSelecte to CustomerInvoice
ProductSelecte.objects.filter(products__customer=self.object.name)
现在您可以从客户那里获得带有商品名称和数量的每次购买
Now you have every purchase from a customer with the name of the item and the quantity
现在在这个查询上使用聚合来获取每个发票,如果你真的需要的话
Now use aggregation on this query to get them per-invoice if you really need that
这篇关于“dict"对象没有属性“order_by"django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!