且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django Rest Framework 在序列化程序中获取用户

更新时间:2023-02-12 21:50:14

CurrentUserDefault 应该适合你.

文档:http://www.django-rest-framework.org/api-guide/validators/#currentuserdefault

请注意:

为了使用它,请求"必须作为实例化序列化器时的上下文字典.

In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer.

如果您正在使用 ModelViewSet 或任何接受 serializer_class 并自动为您初始化的视图/视图集,那么您不必担心.

If you're using ModelViewSet or any view/viewset that takes a serializer_class and automatically initializes it for you, then you don't have to worry about that.

代码示例:

from rest_framework.fields import CurrentUserDefault

class ClientSearchSerializer(serializers.ModelSerializer):

    client = serializers.SlugRelatedField(
        many=False,
        queryset=Client.objects.filter(user=CurrentUserDefault()),
        slug_field='id'
    )