1

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.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
  • is the input a string ? `127.0.0.1:8000/api/stats/?date_after=2022-08-12&date_before=2022-08-29` – D.L Aug 22 '22 at 17:32
  • where do the values `18` and `36` come from ? – D.L Aug 22 '22 at 17:35
  • Those are the values of the total items sold in that given month.Here's how the Order serializer output looks like: { id: 1, date: ‘2022-08-01, products: [ {id: 1, title: ‘T-shirt’, price: 18.00} ]} – Vasko Shelyavski Aug 23 '22 at 06:37
  • ...but we cannot see this in the message. please post the message that contains the information so that users can try to answer the question. – D.L Aug 23 '22 at 06:50

1 Answers1

0

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:

vanbuiten
  • 56
  • 4