[英]Django Rest Framework is owner
I'd like to create a field is_owner
for my serializer which would return whether or not the object being serialized is owned by the user making the request. 我想为我的序列化器创建一个
is_owner
字段,该字段将返回被序列化的对象是否由发出请求的用户拥有。 Something like: 就像是:
"""Defines Some serializer with an owner"""
from rest_framework import serializers
class SomeSerializer(serializers.ModelSerializer):
"""Returns the is_owner field as a boolean"""
is_owner = serializers.SerializerMethodField()
class Meta:
model = SomeModel
fields = ('is_owner',)
def get_is_owner(self, obj):
"""Will return True if the requesting user is the owner, else false"""
return request.user.id == obj.user.id
Is this the way to do it? 这是这样做的方法吗? Should I be passing the
request
object to the serializer to make this work? 我应该将
request
对象传递给序列化程序以使其工作吗? Should I be testing this at the view level? 我应该在视图级别对此进行测试吗?
Thank you! 谢谢!
def get_is_owner(self, obj):
"""
you can pass request in context
"""
return self.context['request'].user.id == obj.user.id
when you call the serializer
pass request
in context
like following code; 当您在类似以下代码的
context
调用serializer
传递request
时;
serializer = SomeSerializer(instance, context={'request': request, ...})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.