当我创建博客帖子时,我还希望自动保存当前用户,而不是手动选择用户作为博客作者。
下面是我代码:
型号.py:
class Blog(models.Model):
author = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
blog_title = models.CharField(max_length=200, unique=True)
序列化程序.py
class BlogSerializer(serializers.ModelSerializer):
class Meta:
model = Blog
查看次数.py
class BlogViewSet(viewsets.ModelViewSet):
queryset = Blog.objects.all().order_by('-id')
serializer_class = BlogSerializer
pagination_class = BlogPagination
lookup_field = 'blog_slug'
def get_permissions(self):
if self.action == 'retrieve':
permission_classes = [IsOwnerOrReadOnly]
elif self.action == 'list':
permission_classes = [IsOwnerOrReadOnly]
else:
permission_classes = [IsOwnerOrReadOnly & IsAuthorGroup]
return [permission() for permission in permission_classes]
1条答案
按热度按时间w46czmvw1#
你可以像下面这样修改你的序列化器。它从请求上下文中选择用户并创建博客。