总结:我正在使用Django Rest框架来创建一个简单的对象(如下所示)。在序列化程序中,我只占用必填字段。但是,我没有在POST响应中返回所有字段(如id,creation_date等)。我只回到了非只读字段。请帮忙:
class Document(models.Model):
owner = models.IntegerField(null=False)
description = models.CharField(max_length=512, blank=True)
created_time = models.DateTimeField(auto_now_add=True)
update_time = models.DateTimeField(auto_now=True)
expiry_time = models.DateTimeField(blank=True, null=True)
status = models.CharField(max_length=128, blank=True)
size = models.IntegerField(blank=True)
type = models.IntegerField(max_length=128, blank=True)
class DocumentCreateSerializer(serializers.ModelSerializer):
class Meta:
model = Document
fields = ('expiry_time', 'description', 'size', 'type', 'status')
read_only_fields = ('id', 'owner', 'created_time', 'update_time')
class DocumentViewSet(viewsets.ModelViewSet):
...
...
def get_serializer_class(self):
if self.request.method == 'POST':
serializer_class = DocumentCreateSerializer
elif self.request.method == 'GET':
serializer_class = DocumentGetSerializer
elif self.request.method == 'PUT':
serializer_class = DocumentUpdateSerializer
elif self.request.method == 'PATCH':
serializer_class = DocumentUpdateSerializer
return serializer_class
答案 0 :(得分:1)
如果您希望返回这些字段,则应将其包含在fields
:
class DocumentCreateSerializer(serializers.ModelSerializer):
class Meta:
model = Document
fields = ('id', 'owner', 'created_time', 'update_time', 'expiry_time',
'description', 'size', 'type', 'status')
read_only_fields = ('id', 'owner', 'created_time', 'update_time')