简体   繁体   中英

Django Rest Framwork get user in serializer

I can get the user in my serializer?

For example I have this serializer:

serializers.py

class ClientSearchSerializer(serializers.ModelSerializer):

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

I can filter my queryset from SlugRelatedField?

CurrentUserDefault should work for you.

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

Please note:

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

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.

Code example:

from rest_framework.fields import CurrentUserDefault

class ClientSearchSerializer(serializers.ModelSerializer):

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

CurrentUserDefault() is a great way to get the user, as has been answered. Another option would be to return a function which returns a serializer class in your view's get_serializer_class method. That way you could supply self.request.user as an argument to the function.

rest_views.py:

class DetailView(generics.RetrieveAPIView):

    def get_serializer_class(self):
        return get_client_search_serializer(user=self.request.user)

    ...

serializers.py:

def get_client_search_serializer(user):
    class ClientSearchSerializer(serializers.ModelSerializer):

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

    return ClientSearchSerializer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM