“dict”对象没有属性“order\u by”Django

2024-10-01 00:16:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想返回一个ManyToMany字段数据,并且我已经使用聚合进行了一些计算,现在我还需要返回产品

这是我的模特

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本书买了2支钢笔,在7月5日,他用2本文案买了1支钢笔,我需要这样的结果:3;pen,3;书籍,2本;文案

我知道我应该使用distinct,我不知道为什么没有任何输出{{clients.items.all|join:','}}? 谢谢你的帮助

已更新

现在我将查询更改为

context['clients'] = ProductSelecte.objects.filter(
    products__customer=self.object.name).values('product').annotate(quantity=Sum(F('qnt'))).order_by('product')

直到在这里工作很好,但我也需要使用这个总价格

.aggregate(
        total_price=Sum(F('price')))

它引起了这个错误

'dict' object has no attribute 'order_by'


Tags: nameobjectmodelsordercustomerproductpriceclass
1条回答
网友
1楼 · 发布于 2024-10-01 00:16:52

改变你的方法。不要从CustomerVoice转到ProductSelecte,而是从ProductSelecte转到CustomerVoice

ProductSelecte.objects.filter(products__customer=self.object.name)

现在,您从客户处购买的每件商品都有商品名称和数量

现在,如果您真的需要,可以在此查询中使用聚合来获取每个发票的数据

相关问题 更多 >