Django rest framework Django,在序列化程序中使用many=True的上下文

Django rest framework Django,在序列化程序中使用many=True的上下文,django-rest-framework,Django Rest Framework,我想在many=True时在序列化程序中设置上下文,但我不知道如何设置 在我的应用程序中,我有多组产品,每种产品都有价格。对于每一组,我都会设置一个包含该组产品的最高和最低价格的上下文。 我请求一个组/api/groups/id或多个/api/groups/?数量=X 我有一个在特定小组提出请求的工作解决方案。正确计算上下文并将其发送到序列化程序 代码如下: 视图: def get(cls, request, pk, format=None): """ R

我想在many=True时在序列化程序中设置上下文,但我不知道如何设置

在我的应用程序中,我有多组产品,每种产品都有价格。对于每一组,我都会设置一个包含该组产品的最高和最低价格的上下文。 我请求一个组/api/groups/id或多个/api/groups/?数量=X

我有一个在特定小组提出请求的工作解决方案。正确计算上下文并将其发送到序列化程序

代码如下:

视图:

    def get(cls, request, pk, format=None):
        """
        Return a specified ProductGroup.
        """

        try:
            product_group = ProductGroup.objects.get(pk=pk)
            serializer = ProductGroupSerializer(product_group, context=get_context(product_group))
# Here context is like : {'lowest_product_price': XX, 'highest_product_price': YY}
            return Response(serializer.data, status=status.HTTP_200_OK)
        except Exception as e:
            raise

        return Response(data={}, status=status.HTTP_204_NO_CONTENT)
序列化程序:

class ProductGroupSerializer(serializers.ModelSerializer):

    lowest_product_price = serializers.SerializerMethodField()
    highest_product_price = serializers.SerializerMethodField()

    def get_lowest_product_price(self, obj):
        return self.context.get('lowest_product_price', '')

    def get_highest_product_price(self, obj):
        return self.context.get('highest_product_price', '')

    class Meta:
        model = ProductGroup
        fields = ('id',
                  'name',
                  'lowest_product_price',
                  'highest_product_price',
                  'creation_date',)
class ProductGroupSerializer(serializers.ModelSerializer):
    lowest_product_price = serializers.SerializerMethodField()
    highest_product_price = serializers.SerializerMethodField()
    def get_lowest_product_price(self, obj):
        context_data = self.context.get(obj.id, None)
        if context_data:
            lowest_product_price = context_data['lowest_product_price']
        else:
            lowest_product_price = ''
        return lowest_product_price
    def get_highest_product_price(self, obj):
        context_data = self.context.get(obj.id, None)
        if context_data:
            highest_product_price = context_data['highest_product_price']
        else:
            highest_product_price = ''
        return highest_product_price
    class Meta:
        model = ProductGroup
        fields = ('id',
                  'name',
                  'lowest_product_price',
                  'highest_product_price',
                  'creation_date')
我不知道在请求多个组时如何处理上下文,然后在设置序列化程序时使用many=True属性

以下是获取组包的实际代码,应更改此代码:

def get(cls, request, format=None):
        """
        List the latest ProductGroups. Returns 'product_group_quantity' number of ProductGroup.
        """

        product_group_quantity = int(request.query_params.get('product_group_quantity', 1))
        product_group_list = ProductGroup.objects.all().order_by('-id')[:product_group_quantity]

        if product_group_list:
            serializer = ProductGroupSerializer(product_group_list, context=???????, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)

        return Response(data={}, status=status.HTTP_204_NO_CONTENT)
感谢Kimamisa的解决方案


基本上,你不需要知道你是在一个多或单一的情况。最好的方法是始终将dict作为上下文传递,并将obj id作为键

序列化程序:

class ProductGroupSerializer(serializers.ModelSerializer):

    lowest_product_price = serializers.SerializerMethodField()
    highest_product_price = serializers.SerializerMethodField()

    def get_lowest_product_price(self, obj):
        return self.context.get('lowest_product_price', '')

    def get_highest_product_price(self, obj):
        return self.context.get('highest_product_price', '')

    class Meta:
        model = ProductGroup
        fields = ('id',
                  'name',
                  'lowest_product_price',
                  'highest_product_price',
                  'creation_date',)
class ProductGroupSerializer(serializers.ModelSerializer):
    lowest_product_price = serializers.SerializerMethodField()
    highest_product_price = serializers.SerializerMethodField()
    def get_lowest_product_price(self, obj):
        context_data = self.context.get(obj.id, None)
        if context_data:
            lowest_product_price = context_data['lowest_product_price']
        else:
            lowest_product_price = ''
        return lowest_product_price
    def get_highest_product_price(self, obj):
        context_data = self.context.get(obj.id, None)
        if context_data:
            highest_product_price = context_data['highest_product_price']
        else:
            highest_product_price = ''
        return highest_product_price
    class Meta:
        model = ProductGroup
        fields = ('id',
                  'name',
                  'lowest_product_price',
                  'highest_product_price',
                  'creation_date')

基本上,你不需要知道你是在一个多或单一的情况。最好的方法是始终将dict作为上下文传递,并将obj id作为键