考虑一个具有配置文件图片和电子邮件字段的用户资源的示例。任何用户都可以看到任何其他用户的个人资料图片,但用户只能看到自己的电子邮件地址。
是否可以设置tastypie,以便根据经过身份验证的用户更改排除的字段集?
我意识到另一种方法是创建单独的完整和受限的用户资源。但目前我只想知道基于用户身份验证限制字段的方法在tastypie中是否可行。
此外,它不一定是排除,同样,有没有一种方法可以根据请求用户更改字段属性?
我认为排除的字段不能以优雅的方式重新出现在画面中。通过在资源中包含get_object_list
,您可能会根据请求使用一些对象操作来操作对象列表
但是,在自定义授权类中使用apply_limits
方法会更好,也更符合逻辑。
是的,有一种方法可以做到这一点。如果您将电子邮件定义为一个单独的字段,而不是用户的字段(可能可以使用,但从未使用过)。您可以在bundle.request包含当前请求的位置定义脱水电子邮件,并且您可以获取该请求。它不会被完全排除为字段,但对于其他字段,它将为None。
我创建了一个ModelResource子类,该子类可以多次继承到所需的ModelResource实例中。类似:
class ResourceThatNeedsToExcludeSomeFields(ExcludeResource, ModelResource):
pass
它通过GET参数(如"&exclude=username")接收要排除的字段
class ExcludeResource(ModelResource):
"""
Generic class to implement exclusion of fields in all the ModelResource classes
All ModelResource classes will be muliple inherited by this class, whose dehydrate method has been overriden
"""
# STACK: How to exclude some fields from a resource list created by tastypie?
def dehydrate(self, bundle):
# I was taking the exclude fields from get paramaters as a comma separated value
if bundle.request.GET.get('exclude'):
exclude_fields = bundle.request.GET.get('exclude').split(',')
for field in exclude_fields:
if str(field) in bundle.data.keys():
del bundle.data[str(field)]
return bundle
您可以修改此项以获得基于用户组的排除字段(或字段所基于的任何标准),如下所示:
class ExcludeResource(ModelResource):
"""
Generic class to implement exclusion of fields in all the ModelResource classes
All ModelResource classes will be muliple inherited by this class, whose dehydrate method has been overriden
"""
# STACK: How to exclude some fields from a resource list created by tastypie?
def dehydrate(self, bundle):
exclude_fields = <get a comma separated list of fields to be excluded based in bundle.request.user>
for field in exclude_fields:
if str(field) in bundle.data.keys():
del bundle.data[str(field)]
return bundle
但是,此代码段不适用于使用"full=True"