[Django]-How to get aggregation in django rest framework inside same api

3πŸ‘

βœ…

in one function you are returning both values, so django wont make it separate and will pass it as a list, if you want different key value pair use this

class CatalogSerializer(serializers.HyperlinkedModelSerializer):
    total_pieces = serializers.SerializerMethodField()
    total_price = serializers.SerializerMethodField()
    class Meta:
        model = Catalog
        fields = '__all__'

    def get_total_pieces(self, obj):
        totalpieces = Catalog.objects.all().aggregate(total_pieces=Count('no_of_pcs'))
        return totalpieces["total_pieces"]
    def get_total_price(self, obj):
        totalprice = Catalog.objects.all().aggregate(total_price=Sum('per_piece_price'))
        return totalprice["total_price"]
πŸ‘€Exprator

Leave a comment