I've got the following function in a manager which seems to work well, 
annotating data and grouping results by "variety name":




def by_variety_and_date(self, start_date, end_date):
    return self.model.objects.filter(
        date__range=(start_date, end_date)
    ).values(
        "variety__name"
    ).annotate(
        total_kgs=Sum('qty_applied'),
        total_profit=Sum('profit'),
        grand_total_cogs=Sum('total_cogs'),
        total_sales=Sum('value'),
    ).order_by('-total_kgs')



However, I would like to add a piece of information like so:



def by_variety_and_date(self, start_date, end_date):
    return self.model.objects.filter(
        date__range=(start_date, end_date)
    ).values(
        "variety__name"
    ).annotate(
        total_kgs=Sum('qty_applied'),
        total_profit=Sum('profit'),
        grand_total_cogs=Sum('total_cogs'),
        total_sales=Sum('value'),
    ).annotate(
        final_margin=Case(
        When(total_sales=0, then=0),
        default=(Sum(F('profit')) / Sum(F('value')))*100
        )
    ).order_by('-total_kgs')


In this case, the grouping doesn't work, and each item is returned separately. 
Essentially `.values().annotate()` works, but `.values().annotate().annotate()` 
seems to break. 


I've also tried `.annotate().annotate().values()` as well to no avail.


Is this the intended behavior? Am I missing a piece of instruction? 


-- 
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 post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/076e99f7-d4e1-431f-9a5e-ccd6106b8eb5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to