问题如下:在下面的代码中我有一个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
和{Categoria_preguntaSerializer
和PersonForPreguntaSerializer
来获取这些字段,但是如果我更改categoria_pregunta
和{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
我建议有两个不同的字段用于读写。您可以在序列化程序
persons_data
中添加一个新字段,该字段可用于获取序列化格式的人员数据列表。在样本代码:
由于您在
Meta
类中使用exclude
,因此persons
字段将包含在读和写操作中,这将接受您在请求json中传递的主键id列表。在{{cd6}和
从文档中
您应该重写
to_representation()
方法请尝试此操作,
相关问题 更多 >
编程相关推荐