Home > Mobile >  How to create a statistics endpoint?
How to create a statistics endpoint?

Time:08-24

I'm learning DRF and I've been stuck on this for a few days. I'm trying to create an endpoint that receives a date range .The response should return a report with the monthly sales distribution for the selected period between date_after and date_before. The value field should contain the total sum of all sold products in this month.

Input:
127.0.0.1:8000/api/stats/?date_after=2022-08-12&date_before=2022-08-29

Desired response:

[
  {
    month: “2022 Jan”,
    value: 18.00
  },
  { 
    month: “2022 Feb”,
    value: 36.00 
  },
]

My models:

class Product(models.Model):
    title = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=1_000, decimal_places=2)

    def __str__(self):
        return self.title


class Order(models.Model):
    date = models.DateField()  # TODO: Add auto_now_add True
    products = models.ManyToManyField(Product, blank=True, related_name='orders')

My viewsets:

class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer


class OrderViewSet(viewsets.ModelViewSet):
    queryset = Order.objects.all().order_by('-date')
    serializer_class = OrderSerializer

My serializers:

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ['id', 'title', 'price']


class OrderSerializer(WritableNestedModelSerializer, serializers.ModelSerializer):
    products = ProductSerializer(many=True, required=False, read_only=False)

    class Meta:
        model = Order
        fields = ['id', 'date', 'products']

I have no idea how to go about this so I've just been blindly scouring the docs.

CodePudding user response:

To add the filters you can use https://github.com/philipn/django-rest-framework-filters

The django-rest-framework-filters package works together with the DjangoFilterBackend class, and allows you to easily create filters across relationships, or create multiple filter lookup types for a given field.

You can than create special summary serializers and use aggregation to get the total values for specific months.

For more information about aggregation look at the django documentation:

  • Related