Django Rest Framwork get user in serializer

痴心易碎 提交于 2020-12-06 12:56:10

问题


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?


回答1:


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'
    )



回答2:


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


来源:https://stackoverflow.com/questions/37613293/django-rest-framwork-get-user-in-serializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!