NotImplemented error combining distinct with annotate

1,433 views
Skip to first unread message

John Gateley

unread,
Jul 21, 2019, 9:20:37 PM7/21/19
to django...@googlegroups.com
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

Simon Charette

unread,
Jul 21, 2019, 9:55:00 PM7/21/19
to Django users
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

John Gateley

unread,
Jul 22, 2019, 9:03:01 AM7/22/19
to django...@googlegroups.com
Thank you Simon, that worked. -- 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 django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/1f28638f-d43e-41d9-ba43-663d9d05df09%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages