'dict' object has no attribute 'order_by' django

点点圈 提交于 2021-01-28 12:14:20

问题


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

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()

and this is my query

context['clients'] = CustomerInvoice.objects.filter(
        customer=self.object.name).aggregate(
            total_order=Sum(F('product__qnt')),
            total_price=Sum(F('product__price')))

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

i know i should use distinct and i dont know why dont have any output {{clients.items.all|join:','}} ? thanks for your helping

updated

now i changed the query to this

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')))

it raise this error

'dict' object has no attribute 'order_by'


回答1:


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



来源:https://stackoverflow.com/questions/62741265/dict-object-has-no-attribute-order-by-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!