Partially annotate django queryset

Asked by At

I have a query that looks like that

TrendData.objects.filter(owner__trend_type__mnemonic='posts').filter(
            date_trend__date__range=[date_from, date_to]).order_by(sort_by)[0: 100].values(
        'owner__name',
        'owner_id',
        'owner__link',
    ).annotate(
        owner_count=Count('owner_id')).annotate(views=Sum('views'), views_u=Sum('views_u'),
                                                likes=Sum('likes'),
                                                shares=Sum('shares'),
                                                interaction_rate=Sum('interaction_rate'),
                                                mean_age=Sum('mean_age')
                                                )

It was worse before, however I have noticed that annotation sums ALL the values in queryset, not the limited queryset that I set before annotation.

Is it possible to annotate only partially , the amount I have limited. My RAW query looks like this

'SELECT "api_trenddata"."id", "api_trenddata"."owner_id",  
 "api_trenddata"."views", "api_trenddata"."views_u",  
 "api_trenddata"."likes", "api_trenddata"."shares",  
 "api_trenddata"."interaction_rate", "api_trenddata"."mean_age",  
 "api_trenddata"."source_id", "api_trenddata"."date_trend",  
 SUM("api_trenddata"."views") AS "views", SUM("api_trenddata"."views_u") AS "views_u",  
 SUM("api_trenddata"."likes") AS "likes", SUM("api_trenddata"."shares") AS "shares", SUM("api_trenddata"."interaction_rate") AS  
 "interaction_rate", SUM("api_trenddata"."mean_age")  
 AS "mean_age" FROM "api_trenddata" INNER JOIN "api_owner" ON  
 ("api_trenddata"."owner_id" = "api_owner"."id") INNER JOIN  
 "api_trendtype" ON ("api_owner"."trend_type_id" =  
 "api_trendtype"."id") 
 WHERE ("api_trendtype"."mnemonic" = posts   AND("api_trenddata"."date_trend" AT TIME ZONE \'UTC\')::date BETWEEN 2019 04-05 AND 2019-04-06) GROUP BY "api_trenddata"."id"'  

0 Answers