我想使用一个序列化程序来创建注释并获取它们的列表。
下面是我的注释序列化程序:
class CommentSerializer(serializers.ModelSerializer):
    creator = UserBaseSerializer(source='author')
    replies = ShortCommentSerializer(many=True, read_only=True)
    reply_on = serializers.PrimaryKeyRelatedField(
        queryset=Comment.objects.all(),
        write_only=True,
        allow_null=True,
        required=False
    )
    author = serializers.PrimaryKeyRelatedField(
        queryset=get_user_model().objects.all(),
        write_only=True
    )
    class Meta:
        model = Comment
        fields = ('id', 'text', 'object_id', 'creator', 'replies', 'reply_on',
                  'author')
        extra_kwargs = {
            'text': {'required': True},
            'object_id': {'read_only': True}
        }
    def create(self, validated_data):
        validated_data.update(
            {'content_type': self.context['content_type'],
             'object_id': self.context['pk']}
        )
        return Comment.objects.create(**validated_data)我的Comment模型有字段author,它是用户模型的FK。在GET方法中,我将creator作为带有source='author'的NestedSerializer返回。此外,我还得到了只写的目的author字段。我正在尝试弄清楚是否可以同时使用author字段进行读写。
发布于 2018-09-11 05:07:42
听起来你想要一台Writable Nested Serializer。通过定义一个已定义的create,您走在了正确的道路上,但是链接的文档应该能够给出一个关于如何实现它的好主意。您可以避免循环遍历可写字段,因为它不是many关系。
发布于 2018-09-11 10:05:19
您可以尝试覆盖方法get_serializer_class,如下所示:
def get_serializer_class(self):
    if self.request.method == 'POST':
        return CommentCreateSerializer
    return CommentSerializer在CommentCreateSerializer中,您可以直接编写author字段。以及仅用于get接口的带有source='author'的CommentSerializer。
跳过此帮助
https://stackoverflow.com/questions/52265338
复制相似问题