如何在has\权限(Django)中获取对象序列化程序

2024-09-27 23:23:54 发布

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

对不起我的英语。我是django的初学者,我不明白为什么它不起作用。我创建自定义权限。在此权限中,我需要获取对象序列化程序的值。例如,我的观点是:

class ProposeFromDealer(generics.CreateAPIView):
    serializer_class = CatInHouseSerializer
    permission_classes = (custom_permissions.CheckExistCatInHouse, permissions.IsAuthenticated)

我的自定义权限

class CheckExistCatInHouse(permissions.BasePermission):
    message = 'Cat not exist in this house'

    def has_object_permission(self, request, view, object):
        current_house = object.house
        house = House.objects.get(id=current_house.id)
        cats_in_house = house.cats.values_list('id')
        current_cat_id = object.cat.id

        if current_cat_id in cats_in_house:
            return True
        else:
            return False

如果猫不在这个房子里,它返回False,如果存在,它返回true。但是我成功了。你知道吗

我可以这样做:

  def has_permission(self, request, view):

但是我不知道如何用这个方法得到object?你知道吗

像这样:

class CheckExistCatInHouse(permissions.BasePermission):
    message = 'Cat not exist in this house'

    def has_opermission(self, request, view):
         object = get_serializer_object() #how i can get object ???
        current_house = object.house
        house = House.objects.get(id=current_house.id)
        cats_in_house = house.cats.values_list('id')
        current_cat_id = object.cat.id

        if current_cat_id in cats_in_house:
            return True
        else:
            return False

Tags: inid权限permissionsgetreturnobjectdef
1条回答
网友
1楼 · 发布于 2024-09-27 23:23:54

您可以这样重写^{}方法:

class CheckExistCatInHouse(permissions.BasePermission):
    message = 'Cat not exist in this house'

    def has_object_permission(self, request, view, obj):
        # __________________________________________^
        cats_in_house = obj.house.cats.values_list('id')
        current_cat_id = obj.cat.id

        return current_cat_id in cats_in_house

重要提示:那么在view中,您应该调用^{},以便调用此权限(CheckExistCatInHouse)。你知道吗

注意:我也简化了你的许可。不需要冗余的查询和if语句。你知道吗

相关问题 更多 >

    热门问题