如何在ListApiView DRF中引发错误

2024-09-30 16:36:44 发布

您现在位置:Python中文网/ 问答频道 /正文

class GetFollowers(ListAPIView):

    """
    Returns the users who follw user,along with weather the visiter — the one who sent api request — 
    follows them or they follow him/her
    """

    permission_classes = [IsAuthenticated,]
    serializer_class = None

    def get_queryset(self,*args,**kwargs):
        user = self.request.data.get('user',None)
        
        if user is None:
            pass

        followers_obj, created = Follow.objects.get_or_create(user=user)
        
        all_followers =  followers_obj.followers.all()

现在,当用户在query_params中发送一个请求以及用户名时,如果发送者没有跟踪他/她想要跟踪的人,我如何返回一个错误


Tags: ortheselfnoneobjgetrequestall
1条回答
网友
1楼 · 发布于 2024-09-30 16:36:44

您可以提出ValidationError

from rest_framework.exceptions import ValidationError


class GetFollowers(ListAPIView):

    """
    Returns the users who follw user,along with weather the visiter — the one who sent api request — 
    follows them or they follow him/her
    """

    permission_classes = [IsAuthenticated,]
    serializer_class = None

    def get_queryset(self, *args, **kwargs):
        # some code
        if not_followed_condition:  # I hope you know what you need to check here
            raise ValidationError(
                {'permission denied': "Can't see user's followers"}
            )
        # some other code
        return queryset

        

相关问题 更多 >