django rest framework 针对当前用户进行过滤
Published on Aug. 22, 2023, 12:12 p.m.
django rest framework 针对当前用户进行过滤
你可能想过滤queryset,以确保只返回与当前认证的用户有关的结果。
你可以通过基于request.user的值进行过滤来做到这一点。
示例:
from myapp.models import Purchase
from myapp.serializers import PurchaseSerializer
from rest_framework import generics
class PurchaseList(generics.ListAPIView):
serializer_class = PurchaseSerializer
def get_queryset(self):
"""
This view should return a list of all the purchases
for the currently authenticated user.
"""
user = self.request.user
return Purchase.objects.filter(purchaser=user)
代码来源
https://www.django-rest-framework.org/api-guide/filtering/#filtering-against-the-current-user