更改Django Rest Framework默认模型序列号返回的JSON结构有什么好方法?
示例 -
DRF现在返回的餐厅对象:
{
"id":9,
"label":"Pizza Hut"
"like_id:":32,
"like_quantity":2
}
更理想的json结构:
{
"id":9,
"label":"Pizza Hut",
"social": {
"like_id:":32,
"like_quantity":2
}
}
要制作json结构,我希望默认JSON中的少数字段嵌套在新字段下。
答案 0 :(得分:1)
如果你说得对,你想要这个:
{
"id":9,
"label":"Pizza Hut",
"social": {
"like_id:":32,
"like_quantity":2
}
}
是GET请求的结果。
如果您使用的是通用视图,则可以编辑返回值,例如:
class RestaurantViewSet(mixins.RetrieveModelMixin,
viewsets.GenericViewSet):
queryset = Restaurant.objects.all()
serializer_class = RestaurantSerializer
def retrieve(self, request, pk=None):
queryset = Restaurant.objects.all()
restaurant = get_object_or_404(queryset, pk=pk)
serializer = RestaurantSerializer(user,context={'request': request})
results = {
"id":serializer.data['id'],
"label":serializer.data['label'],
"social": {
"like_id:":serializer.data['like_id'],
"like_quantity":serializer.data['like_quantity']
}
}
return Response(results)
答案 1 :(得分:1)
更好的解决方案是在SerializerMethod
中使用Serializer
。例如:
class RestaurantSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(source='id')
label = serializers.CharField(source='label')
social = serializers.SerializerMethod(method_name='pick_social_fields')
def is_restaurant_liked(self, restaurant):
# some logic here
return is_liked
def pick_social_fields(self, restaurant):
like_id = self.is_restaurant_liked(restaurant)
like_quantity = restaurant.like_set.count
return {
'like_id': like_id,
'like_quantity': like_quantity
}
这个解决方案对我来说更好,因为您不必在DRF视图中覆盖任何内容。您只需要在Serializer
类中定义一个方法。