django-rest-framework - 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')
解决方案
基本上,您不需要知道您是在多例还是单例中。最好的方法是始终将 dict 作为上下文传递,并以 obj id 作为键
推荐阅读
- java - 如何在 Appconstants 类中动态创建基本 url
- python - 从 Numpy 或 Tensorflow 中的线性阵列矢量化创建对角方形阵列
- android - 动态字段数据保存到android中的Web服务
- python - 显示函数的参数
- python - 导入张量流在Windows中给出错误
- reactjs - Semantic-UI Table,持久排序
- reactjs - 如何在 React 中检查动态生成的复选框时有条件地呈现额外的表单选项?
- calendar - 为事件重叠vtiger日历创建弹出窗口
- azure-active-directory - 新创建的 Azure 应用注册的 DiscoveryFailedException
- html - SVG中的动画延迟不受尊重