首页 > 解决方案 > Django,在序列化程序中使用上下文,many=True

问题描述

我想在序列化程序中设置一个上下文,而 many=True 但我不知道该怎么做。

在我的应用程序中,我有一组产品,每个产品都有价格。对于每个组,我都设置了一个包含该组产品最高和最低价格的上下文。我请求一组 (/api/groups/id) 或多组 (/api/groups/?quantity=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',)

当请求多个组时,我不知道如何处理上下文,然后我在设置序列化程序时使用 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):
        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')

标签: django-rest-framework

解决方案


基本上,您不需要知道您是在多例还是单例中。最好的方法是始终将 dict 作为上下文传递,并以 obj id 作为键


推荐阅读