Closed wasabigeek closed 6 years ago
I think you can accomplish want you want already because you can pivot on an annotated column.
from django.db.models import Case, When, CharField
annotation = {
'pivot_column': Case(When(Q(stage='negotiating', is_archived=False), then=Value('Negotiating')),
When(Q(...), then=Value('Closed'),
When(Q(...), then=Value('Archived'),
default=None,
output_field=CharField()
}
queryset = Lead.objects.annotate(**annotation)
pivot_table = pivot(queryset, 'sales_rep', 'pivot_column', 'id', aggregation=Count)
If there is a cleaner API than the above, maybe it's worth having the pivot package expose that. I'm certainly open to making pivoting on an annotated column cleaner, but I'm not thinking of something better off the top of my head. The cases
list in your example isn't that different than what's in the annotation.
@wasabigeek I forgot to say, let me know if the above works for you or not.
@martsberger it works! Just a few typos in the example e.g. When
was not closed properly.
I was able to create the "Whens" programmatically and use those :)
whens = [
When(Q(stage='negotiating', is_archived=False), then=Value('Negotiating')),
When(Q(...), then=Value('Closed')),
When(Q(...), then=Value('Archived')),
]
...
queryset = Lead.objects.annotate(pivot_column=Case(*whens, default=None, output_field=CharField())
Do you think it would be possible to specify a dict of
when/then
options in place ofrow
/column
. Use case below:Data
Result
So perhaps something like:
What do you think?
P.S. Thanks for this package! Was looking for something lightweight for a lightweight use case, and this is great.