2017-08-22 3 views
-1

私の英語を残念に思う。私はdjangoの初心者です、なぜ私は仕事をしないのか分かりません。私はカスタムの権限を作成します。この許可では、私はオブジェクトシリアライザの値を取得する必要があります。例えば、その私の見解:存在する場合は、この家の中で、真の猫を存在doesntの場合どのように私はオブジェクトのシリアライザを取得できますhas_permission(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を返します。しかし、許可の成功。

私はこのような方法を行うことができます。

def has_permission(self, request, view): 

しかし、私はこの方法でobjectを得ることができる方法を知っていけませんか?

このよう

:重要

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(この権限を呼び出すためにself.check_object_permissions(request, obj)を呼び出す必要があります。このようなhas_object_permission()メソッドをオーバーライドすることができます

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 

答えて

0

)。

注::あなたの許可も簡素化されました。冗長クエリやifステートメントは不要です。

関連する問題