Django REST框架中的每个字段权限 [英] Per Field Permission in Django REST Framework
问题描述
我发现最接近的建议是 https://groups.google.com/forum/#!topic/django-rest-framework/FUd27n_k3U0 更改了序列化程序根据请求类型。这对我的情况是不会奏效的,因为我没有查询器或对象,以确定是否由用户拥有。
当然我有我的前端隐藏私人信息,但聪明的人仍然可以窥探API请求来获取完整的对象。如果需要代码,我可以提供它,但是我的请求适用于vanilla Django REST框架设计。
我想出了一种方式去做吧。在序列化器中,我可以访问进行API请求的对象和用户。因此,我可以检查请求者是否是对象的所有者,并返回私人信息。如果没有,序列化器将返回一个空字符串。
class UserInfoSerializer(serializers.HyperlinkedModelSerializer):
private_field1 = serializers.SerializerMethodField('get_private_field1')
class Meta:
model = UserInfo
fields =(
'id',
'public_field1'
'public_field2',
'private_field1',
)
read_only_fields =('id')
def get_private_field1(self,obj):
#obj.created_by是用户模型的外键
如果obj.created_by!= self.context ['request']。user:
return
else:
return obj.private_field1
I am using Django REST Framework to serialize a Django model. I have a ListCreateAPIView view to list the objects and a RetrieveUpdateDestroyAPIView view to retrieve/update/delete individual objects. The model stores information that the users submit themselves. The information they submit contains some private information and some public information. I want all users to be able to list and retrieve the public information but I want only the owner to list/retrieve/update/delete the private information. Therefore, I need per-field permissions and not object permissions.
The closest suggestion I found was https://groups.google.com/forum/#!topic/django-rest-framework/FUd27n_k3U0 which changes the serializer based on the request type. This won't work for my situation because I don't have the queryset or object at that point to determine if it is owned by the user or not.
Of course, I have my frontend hiding the private information but smart people can still snoop the API requests to get the full objects. If code is needed, I can provide it but my request applies to vanilla Django REST Framework designs.
I figured out a way to do it. In the serializer, I have access to both the object and the user making the API request. I can therefore check if the requestor is the owner of the object and return the private information. If they are not, the serializer will return an empty string.
class UserInfoSerializer(serializers.HyperlinkedModelSerializer):
private_field1 = serializers.SerializerMethodField('get_private_field1')
class Meta:
model = UserInfo
fields = (
'id',
'public_field1',
'public_field2',
'private_field1',
)
read_only_fields = ('id')
def get_private_field1(self, obj):
# obj.created_by is the foreign key to the user model
if obj.created_by != self.context['request'].user:
return ""
else:
return obj.private_field1
这篇关于Django REST框架中的每个字段权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!