必要な 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」で指定された関連リソースでは機能しません