Django Rest序列化程序:在GET上而不是POST上使用嵌套序列化程序

2024-09-29 23:26:37 发布

您现在位置:Python中文网/ 问答频道 /正文

问题如下:在下面的代码中我有一个PreguntaSerializer。如果我发布这样一个JSON,它现在是这样编码的:

{
    "categoria_pregunta": 1,
    "titulo": "Pregunta de Prueba",
    "descripcion": "Esta es la pregunta que mando por Postman",
    "persons": [1, 3, 5, 3050]
}

一切正常,但是当我检索数据时,我得到categoria_pregunta和{}的方式与我发布它们的方式相同(分别为int和array)。我希望能够使用Categoria_preguntaSerializerPersonForPreguntaSerializer来获取这些字段,但是如果我更改categoria_pregunta和{}作为它们各自的序列化程序,则在发布前面提到的JSON时会出错。 有没有一种方法可以对这两个操作使用相同的PreguntaSerializer,还是应该将GET和{}的视图分开并使用不同的序列化程序?在

模型.py

^{pr2}$

序列化程序.py

class Categoria_preguntaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Categoria_pregunta
        fields = ('id', 'nombre',)

class PersonForPreguntaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields = ('id', 'name', 'lastname')

class PreguntaSerializer(serializers.ModelSerializer):
    usuario = UserSerializer(read_only=True)
    categoria_pregunta = serializers.PrimaryKeyRelatedField(queryset=Categoria_pregunta.objects.all())
    persons = serializers.PrimaryKeyRelatedField(many=True, queryset=Person.objects.all())

    class Meta:
        model = Pregunta
        exclude = ('status', )

视图.py

class ListaPregunta(ListCreateAPIView):
    queryset = Pregunta.objects.all().order_by('-id')
    serializer_class = PreguntaSerializer

Tags: py程序idmodel序列化metaclassqueryset
2条回答

我建议有两个不同的字段用于读写。您可以在序列化程序persons_data中添加一个新字段,该字段可用于获取序列化格式的人员数据列表。在

样本代码:

class PreguntaSerializer(serializers.ModelSerializer):
    usuario = UserSerializer(read_only=True)
    categoria_pregunta = serializers.PrimaryKeyRelatedField(queryset=Categoria_pregunta.objects.all())
    persons_data = PersonForPreguntaSerializer(source='persons', many=True, read_only=True)

    class Meta:
        model = Pregunta
        exclude = ('status', )

由于您在Meta类中使用exclude,因此persons字段将包含在读和写操作中,这将接受您在请求json中传递的主键id列表。在

{{cd6}和

从文档中

.to_representation() - Override this to support serialization, for read operations. .to_internal_value() - Override this to support deserialization, for write operations.

您应该重写to_representation()方法
请尝试此操作,

from rest_framework.serializers import Serializer


class PreguntaSerializer(serializers.ModelSerializer):
    usuario = UserSerializer(read_only=True)
    categoria_pregunta = serializers.PrimaryKeyRelatedField(queryset=Categoria_pregunta.objects.all())
    persons = serializers.PrimaryKeyRelatedField(many=True, queryset=Person.objects.all())

    class Meta:
        model = Pregunta
        fields = '__all__'

    def to_representation(self, instance):
        if self.context['request'].method == 'POST':
            user = UserSerializer(instance.usuario).data
            categoria_pregunta = Categoria_preguntaSerializer(instance.categoria_pregunta).data
            persons = PersonForPreguntaSerializer(instance.persons, many=True).data
            data = {"id": instance.id,
                    "usuario": user,
                    "categoria_pregunta": categoria_pregunta,
                    "persons": persons,
                    "titulo": instance.titulo,
                    "descripcion": instance.descripcion
                    }
            return data
        return Serializer.to_representation(self, instance)

相关问题 更多 >

    热门问题