Aggregate (and other annotated) fields in Django Rest Framework serializers

后端 未结 3 1944
不思量自难忘°
不思量自难忘° 2020-11-29 18:20

I am trying to figure out the best way to add annotated fields, such as any aggregated (calculated) fields to DRF (Model)Serializers. My use case is simply a situation where

3条回答
  •  时光取名叫无心
    2020-11-29 18:36

    Possible solution:

    views.py

    class IceCreamCompanyViewSet(viewsets.ModelViewSet):
        queryset = IceCreamCompany.objects.all()
        serializer_class = IceCreamCompanySerializer
    
        def get_queryset(self):
            return IceCreamCompany.objects.annotate(
                total_trucks=Count('trucks'),
                total_capacity=Sum('trucks__capacity')
            )
    

    serializers.py

    class IceCreamCompanySerializer(serializers.ModelSerializer):
        total_trucks = serializers.IntegerField()
        total_capacity = serializers.IntegerField()
    
        class Meta:
            model = IceCreamCompany
            fields = ('name', 'total_trucks', 'total_capacity')
    

    By using Serializer fields I got a small example to work. The fields must be declared as the serializer's class attributes so DRF won't throw an error about them not existing in the IceCreamCompany model.

提交回复
热议问题