问题
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