gpt4 book ai didi

django - 如何进行 Django REST 框架/me/调用?

转载 作者:行者123 更新时间:2023-12-03 18:30:01 26 4
gpt4 key购买 nike

假设我有一个 ViewSet :

class ProfileViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows a user's profile to be viewed or edited.
"""
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)
queryset = Profile.objects.all()
serializer_class = ProfileSerializer

def perform_create(self, serializer):
serializer.save(user=self.request.user)

...和 ​​ HyperlinkedModelSerializer :
class ProfileSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Profile
read_only_fields = ('user',)

我有我的 urls.py设置为:
router.register(r'profiles', api.ProfileViewSet, base_name='profile')

这让我可以访问例如 /api/profile/1/美好的。

我想在我的 API(类似于 Facebook API 的 /me/ 调用)上设置一个新的端点 /api/profile/me/访问当前用户的个人资料 - 如何使用 Django REST Framework 执行此操作?

最佳答案

使用@Gerard 的解决方案给我带来了麻烦:

Expected view UserViewSet to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly..

看看 source code for retrieve()好像是 user_id未使用(未使用 *args)

此解决方案有效:
from django.contrib.auth import get_user_model
from django.shortcuts import get_object_or_404

from rest_framework import filters
from rest_framework import viewsets
from rest_framework import mixins
from rest_framework.decorators import list_route
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from ..serializers import UserSerializer


class UserViewSet(viewsets.ModelViewSet):
"""
A viewset for viewing and editing user instances.
"""
serializer_class = UserSerializer
User = get_user_model()
queryset = User.objects.all()
filter_backends = (filters.DjangoFilterBackend, filters.SearchFilter)
filter_fields = ('username', 'email', 'usertype')
search_fields = ('username', 'email', 'usertype')

@list_route(permission_classes=[IsAuthenticated])
def me(self, request, *args, **kwargs):
User = get_user_model()
self.object = get_object_or_404(User, pk=request.user.id)
serializer = self.get_serializer(self.object)
return Response(serializer.data)

访问 /api/users/me回复与 /api/users/1 相同的数据(当登录用户是 pk=1 的用户时)

关于django - 如何进行 Django REST 框架/me/调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30170848/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com