I have a model name Transaction with a group field (foreign key), product field (foreign key) and a quantity field (integer).
I want to sum the quantity of each product of each group. The Custom QuerySet method below works, but I would like to return the product instance instead of a string of it’s name to be able to in the template access other fields and properties without defining them here. Is it possible in any way?
class TransactionQuerySet(models.QuerySet):
def group_quantity_dict(self):
return (self
.values('group__name', 'product__name')
.annotate(qty=Sum('quantity')
Ok, a “group by” aggregation in SQL doesn’t return instances of tables in the database, it’s returning a result set synthesized from the query results.
What this means is that you don’t get back model instances from the ORM. You’re going to need to make an extra query to retrieve those referenced models.
The result above, gets me the sum I want. If I were to do this in a Subquery and annotate this sum to each row of the query set, I would have multiple lines of each product in each group. I can not use distinct to remove the “extra” rows, unless I switch to PostgreSQL db, since they are not duplicates, they have unique id and probably different quantities. Without moving to PostgreSQL, .distinct(product, group) in PostgreSQL, is there something more generic that I could do that achieves the same thing?