Assuming you have a model definition `Salesperson` you could use
Salesperson.object.annotate(
sales_amount=Sum('sales__sales_amount'),
)
But given you mentioned 'salesperson' is a text field you can do
persons = Sales.objects.values('salesperson').annotate(
sum_sales_amount=Sum('sales_amount')
)
for person in persons:
print('Salesperson %s sold %d dollars' % (person['salesperson'],
person['sum_sales_amount'])
Note that .values() before annotating a an aggregation function results in
a GROUP BY
which should should prefer over using DISTINCT.
Cheers,
Simon
Le dimanche 21 juillet 2019 21:20:37 UTC-4, John Gateley a écrit :
>
> Hello,
>
> Python version: Python 3.7.2
> Django version: 2.2.3
>
> I want to combine distinct and annotate(Sum(...)), and get the following
> error:
> NotImplementedError: annotate() + distinct(fields) is not implemented.
>
> To describe: I have a bunch of sales entries like:
> 'John', 100
> 'Sam', 50
> 'John', 200
> (the model is a text field for salesperson and an integer field for
> sales_amount)
>
> I want to write a query like:
> res = Sales.objects.distinct('salesperson').annotate(Sum('sales_amount'))
> for person in res:
> print('Salesperson %s sold %d dollars' % (person.salesperson,
> person.sales_amount__count))
>
> I would expect:
> Salesperson John sold 300 dollars
> Salesperson Sam sold 50 dollars
>
> Instead it generates the above error. Is there a way to do this?
>
> Thank you,
>
> John
>
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-users/1f28638f-d43e-41d9-ba43-663d9d05df09%40googlegroups.com.