问题
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