gpt4 book ai didi

python - Django Rest 序列化程序 : Use nested serializer on GET but not POST

转载 作者:行者123 更新时间:2023-12-05 02:16:51 25 4
gpt4 key购买 nike

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

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

一切正常,但是当我检索数据时,我得到了 categoria_preguntapersons 与我发布它们的方式相同(分别作为 int 和数组)。我希望能够使用 Categoria_preguntaSerializerPersonForPreguntaSerializer 获取这些字段,但是如果我更改 categoria_preguntapersonsPreguntaSerializer 中用于各自的序列化程序,在发布前面提到的 JSON 时出现错误。有没有一种方法可以对这两个操作使用相同的 PreguntaSerializer,或者我应该将 GETPOST 的 View 分开并使用不同的序列化器?

模型.py

class Categoria_pregunta(models.Model):
nombre = models.CharField(
'Descripcion', null=True, blank=True, max_length=150, default='')
status = models.IntegerField(
'Estado', null=True, blank=True, choices=STATUS_CHOICES)

class Pregunta(models.Model):
titulo = models.CharField(max_length=200, null=False, blank=False, default='')
descripcion = models.TextField(null=False, blank=False)
categoria_pregunta = models.ForeignKey(
Categoria_pregunta, null=True, blank=False, max_length=20)
usuario = models.ForeignKey(User, null=True, blank=False, max_length=20)
persons = models.ManyToManyField(Person, blank=False, max_length=20)

class Person(models.Model):
name = models.CharField('Nombre', null=True,
blank=False, max_length=1000, default='')
lastname = models.CharField(
'Apellido', null=True, blank=False, max_length=1000, default='')
...

serializers.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', )

views.py

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

最佳答案

你应该覆盖 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)

关于python - Django Rest 序列化程序 : Use nested serializer on GET but not POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48940669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com