【问题标题】:How can I get the count of nested model relationship?如何获得嵌套模型关系的计数?
【发布时间】:2020-09-02 23:05:23
【问题描述】:

这是我的模特关系:

|---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

现在我想在每个产品中获取计数优惠券。我该怎么办?

【问题讨论】:

标签: django


【解决方案1】:

将以下行添加到您的ProductSerializer

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

instance.coupon_set.all().count() 中的coupon_set 重命名为您的后向关系名称。默认名称为coupon_set,但您可以通过在与Product 模型相关的Coupon 模型中指定related_name 来更改它

【讨论】:

  • 非常感谢。它有效,但我想我应该编辑我的问题标题你能帮我吗?
猜你喜欢
  • 1970-01-01
  • 2020-04-04
  • 2020-04-22
  • 1970-01-01
  • 1970-01-01
  • 2016-09-26
  • 2023-02-20
  • 2017-06-07
  • 1970-01-01
相关资源
最近更新 更多