python / 开发 · 12月 24, 2022 0

django rest framework 针对当前用户进行过滤

内容纲要

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

%d 博主赞过: