[Answered ]-Custom django_filters (how to sum filters result)

0👍

I could solve the problem by overriding get_queryset method:

def get_queryset(self, request, *args, **kwargs):
    queryset = StoreAnalytics.objects.filter(store__user_id=self.request.user.pk)
    for backend in list(self.filter_backends):
        stores_sales = backend().filter_queryset(self.request, queryset, self).aggregate(accruals_sum=Sum(F("accruals_sum")), sold_products=Sum(F("sold_products")),  taxes_summ=Sum(F("taxes_count")))
return queryset

1👍

You can use a BaseInFilter:

from django_filters.filter import BaseInFilter


class StoreAnalyticsFilter(filters.FilterSet):
    store_ids = BaseInFilter(field_name='store_id')

You then filter with:

api/v1/analytics/?store_ids=1,2

for the queryset, use the super method:

class StoreAnalyticsApi(ListCreateAPIView):
    permission_classes = (IsAuthenticated,)
    http_method_names = ["get"]
    serializer_class = StoreAnalyticsSerializer
    filter_backends = (DjangoFilterBackend,)
    filterset_class = StoreAnalyticsFilter

    def get_queryset(self):
        queryset = (
            super()
            .get_queryset()
            .filter(store__user_id=self.request.user.pk)
            .aggregate(
                accruals_sum=Sum(F("accruals_sum")),
                sold_products=Sum(F("sold_products")),
                taxes_summ=Sum(F("taxes_count")),
            )
        )

        # {'accruals_sum': Decimal('10045'), 'sold_products': 68, 'taxes_summ': Decimal('602.700000000000')}
        return queryset

Leave a comment