在哪里设置作者为 request.user

Where to set the author as request.user

问题

在我的模型中,我有一个作者字段,我想将其作为 ForeignKey 输入到 UserModel 中,用户已通过 JWT 令牌对自己进行身份验证。我的 API 和 JWT 身份验证工作正常,但我不知道在哪里设置后端的 author = request.user


我的代码:

apis.py

class AlarmstichworteCreateApi(ApiErrorsMixin, APIView):
    permission_classes = [IsAuthenticated]

    class InputSerializer(serializers.ModelSerializer):

        author = UserListAPI.OutputSerializer(source='UserListAPI_set', many=True)
        created = serializers.DateTimeField()
        updated = serializers.DateTimeField()
        name = serializers.CharField(max_length=100)
        class Meta:
            model = AlarmstichworteConfig
            fields = (
                '__all__'
            )

    def post(self, request, *args, **kwargs):
        serializer = self.InputSerializer(data=request.data)
#!      serializer = self.InputSerializer(data=request.data, author=request.user) # Try 1
        serializer.is_valid(raise_exception=True)

        create_alarmstichwort(**serializer.validated_data)
#!      create_alarmstichwort(**serializer.validated_data, author=request.user) # Try 1

        return Response(status=status.HTTP_201_CREATED)

services.py

def create_alarmstichwort(
    *,
    author: ForeignKey,
    created: datetime,
    updated: datetime,
    name: str,

) -> AlarmstichworteConfig:

    if AlarmstichworteConfig.objects.filter(id=id).exists():
        raise ValidationError('Alarmstichwort existiert bereits')

    alarmstichwort = AlarmstichworteConfig.objects.create(
        author=author,
        created=created,
        updated=updated,
        name=name,
    )
    alarmstichwort.full_clean()
    alarmstichwort.save()

    return alarmstichwort

如果有人能帮助我,我会很高兴。非常感谢!

感谢您在评论中的澄清。如果您从序列化程序中删除 author 字段,然后将其作为参数传递给 create_alarmstichwort,就像您之前尝试使用来自 request.user 的值一样,您将得到您想要的结果我喜欢。这确实意味着您需要停止使用 fields = "__all__".