我如何在has_permission(Django)中获取对象序列化程序

时间:2017-08-22 18:29:03

标签: python django

抱歉我的英文。我是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

如果cat在这个房子里不存在,它返回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

1 个答案:

答案 0 :(得分:0)

您可以像这样覆盖has_object_permission()方法:

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中,您应致电self.check_object_permissions(request, obj)以致取得此权限(CheckExistCatInHouse)。

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