我试图做的是在创建新帖子时自动设置django设置作者字段,但由于某种原因(它已经工作了一段时间,我还没有触及后端部分一段时间,因为我现在在前端工作),出现了错误, save()得到了一个意想不到的关键字参数' author' 。
如果我只留下serializer.save()
,当然,我必须自己选择作者,但在这种情况下我也会收到错误 save()缺少1个必要的位置参数:' kwargs' 即可。
通过将此问题添加到 serializers.py
extra_kwargs = {
'author': {
'default': serializers.CreateOnlyDefault(
serializers.CurrentUserDefault()
),
'read_only': True
}
}
但是在这种情况下,我的api中没有正确的作者序列化(我只有作者的id,而不是完全序列化的作者模型)
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],
)
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', )
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)
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'
},
}