这是我的模型关系:
|---Retailer
|---Product
|---Coupon
现在,我有一个观点可以让我将每个零售商的产品归还给我:
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)
这是RetailerSerializer:
class RetailerSerializer(serializers.ModelSerializer):
products = ProductSerializer(many=True, read_only=True)
class Meta:
model = Retailer
fields = ['name', 'website','description', 'products']
depth = 1
现在,我想在每种产品中获得计数优惠券。我该怎么办?
答案 0 :(得分:1)
将以下行添加到您的ProductSerializer
def to_representation(self, instance):
reps = super().to_representation(instance)
reps['coupons_count'] = instance.coupon_set.all().count()
return reps
用您的后向关系名称重命名coupon_set
中的instance.coupon_set.all().count()
。默认名称为coupon_set
,但是您可以通过在related_name
模型中指定与Coupon
模型相关的Product
来更改它。