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

基本上,您不需要知道您是在多个案例还是单个案例中。最好的方法是始终将字典作为上下文传递,将 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')

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

最新更新