-1

Here are my model relationships:

|---Retailer
    |---Product
        |---Coupon

Now I have a view that returns me each retailer with its products:

class ProductList(APIView):
    def get(self, request):
        retailer = Retailer.objects.all()
        serializer = RetailerSerializer(retailer, many=True)
        data = serializer.data
        return JsonResponse({'data': data}, safe=False)

And here's RetailerSerializer:

class RetailerSerializer(serializers.ModelSerializer):
    products = ProductSerializer(many=True, read_only=True)
    class Meta:
        model = Retailer
        fields = ['name', 'website','description', 'products']
        depth = 1

Now I want to get count coupons in each product. What should i do?

Vala Khosravi
  • 2,352
  • 3
  • 22
  • 49

1 Answers1

1

Add following line into your ProductSerializer

def to_representation(self, instance):
    reps = super().to_representation(instance)
    reps['coupons_count'] = instance.coupon_set.all().count()
    return reps

Rename coupon_set in instance.coupon_set.all().count() with your backward relation name. The default name is coupon_set but you can change it by specify related_name in Coupon model that related into Product model

Eby Sofyan
  • 434
  • 4
  • 8