Django休息框架嵌套在非模型序列化器内的序列化器

时间:2017-06-13 12:38:18

标签: django django-rest-framework

我有一个页面,其中几个单独的序列化器,他们没有关系。我不是一个一个地调用它们,而是想立刻调用它们(仅用于列表,而不是用于写入。不要担心写作)。

因此,想要创建一个单独的序列化程序,其中每个都作为字段(嵌套序列化程序)。

像这样:

class MarkSerializer(serializers.ModelSerializer):
     # Shows list of marks
     class Meta:
         model = Mark
         fields = blah blah

class TopCricketerSerializer(serializers.ModelSerializer):
    # Show list of top cricketers


and more..

这是我正在计划的常见序列化器:

CommonSerializer(serializers.Serializer): # Correct me if am using wrong serializer of if no serializer needed 
    marks = MarkSerializer(many=True)
    top_cricketers = TopCricketerSerializer(many=True)
    # more such non-related fields

如果我不清楚,请告诉我。

2 个答案:

答案 0 :(得分:0)

您的序列化程序对于只读操作看起来很好。有关详细信息,请参阅this answer

要使此序列化程序可写(如果有必要),您需要在create上添加update和/或CommonSerializer方法in the docs

答案 1 :(得分:0)

你理解正确。这是它的外观示例

# serializers.py
from rest_framework import serializers
from .models import Mark, TopCricketer

class MarkSerializer(serializers.ModelSerializer):
    class Meta:
        model = Mark
        fields = "__all__"

class TopCricketerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Mark
        fields = "__all__"

class CommonSerializer(serializers.Serializer):
    marks = MarkSerializer(many=True)
    top_cricketers = TopCricketerSerializer(many=True)

    def create(self, validated_data):
        marks = MarkSerializer(data=validated_data['marks'], many=True)
        marks.is_valid(raise_exception=True)
        marks.save()

        top_cricketers = TopCricketerSerializer(data=validated_data['top_cricketers '], many=True)
        top_cricketers.is_valid(raise_exception=True)
        top_cricketers.save()

        return self.__class__({'marks': marks, 'top_cricketers ': top_cricketers})

# views.py
from rest_framework import generics, status
from rest_framework.response import Response
from .serializers import CommonSerializer
from .models import Mark, TopCricketer


class CommonAPIView(generics.GenericAPIView):
    serializer_class = CommonSerializer
    
    # retrieve
    def get(self, request, *args, **kwargs):
        marks = Mark.objects.all()
        top_cricketers = TopCricketer.objects.all()
        serializer= self.get_serializer({'marks': marks, 'top_cricketers ': top_cricketers})
        return Response(serializer.data)
   
   # create
   def post(self, request, *args, **kwargs):
        serializer= self.get_serializer(data = request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)