save()得到了一个意想不到的关键字参数' author'

时间:2018-06-18 20:30:34

标签: python django-rest-framework

我试图做的是在创建新帖子时自动设置django设置作者字段,但由于某种原因(它已经工作了一段时间,我还没有触及后端部分一段时间,因为我现在在前端工作),出现了错误, save()得到了一个意想不到的关键字参数' author' 。 如果我只留下serializer.save(),当然,我必须自己选择作者,但在这种情况下我也会收到错误 save()缺少1个必要的位置参数:' kwargs' 即可。 通过将此问题添加到 serializers.py

的末尾,我找到了解决此问题的奇怪方法
        extra_kwargs = {
        'author': {
            'default': serializers.CreateOnlyDefault(
                serializers.CurrentUserDefault()
            ),
            'read_only': True
        }
    }

但是在这种情况下,我的api中没有正确的作者序列化(我只有作者的id,而不是完全序列化的作者模型)

models.py:

class Post (AuthorMixin, PublicationMixin, DateTimeMixin,
        CommentMixin, LikeMixin, ShowMixin, EventMixin):
title = models.CharField(max_length=255)
comments = GenericRelation(Comment)

def get_title(self):
    return "%s posted %s" %\
           (self.get_author(),
            self.title[0:15:1],
            )

serializers.py:

class SimplePostSerializer(serializers.ModelSerializer):
author = SimpleUserSerializer(read_only=True)

class Meta:
    model = Post

    fields = (
                'url', 'author', 'title', 'created_at',
                'text', 'comments_count', 'likes_count',
             )

    read_only_fields = ('comments_count', 'likes_count', )

views.py

class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = SimplePostSerializer
permission_classes = (IsOwnerOrReadOnly, permissions.IsAuthenticatedOrReadOnly)

def get_serializer_class(self):
    print(self.action)
    if self.action == 'retrieve':
        return PostSerializer
    else:
        return SimplePostSerializer

def get_queryset(self):
    return Post.objects.filter(author=self.request.user). \
        prefetch_related('author', 'author__avatar', 'comments') \
        if self.action == 'mine' \
        else Post.objects.all() \
        .prefetch_related('author', 'author__avatar', 'comments') \
        .filter(to_show=True)

def perform_create(self, serializer):
    serializer.save(author=self.request.user)

@list_route(methods=['get'],
            permission_classes=[permissions.IsAuthenticated])
def mine(self, request):
    serializer = self.get_serializer(self.get_queryset(), many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)

作者的SimpleUserSerializer

class SimpleUserSerializer(serializers.ModelSerializer):
avatar = AvatarSerializer(many=True)

class Meta:
    model = CustomUser
    fields = ('url', 'username', 'email', 'avatar')
    read_only_fields = ('id', 'email',)
    extra_kwargs = {
        'url': {
            'lookup_field': 'username'
        },
    }

0 个答案:

没有答案