我有一些Tastypie资源在调用时会呈现类似的内容:
{
"meta":{
"limit":1,
"next":"/api/v1/studio/?limit=1&offset=1",
"offset":0,
"previous":null,
"total_count":93
},
"objects":[
{
"full_address":"1234 Main St.",
"resource_uri":"/api/v1/studio/3/",
"state":{
"resource_uri":"/api/v1/state/110/",
"state_id":110,
"state_name":"Colorado",
"studios":[
"/api/v1/studio/3/",
"/api/v1/studio/4/",
"/api/v1/studio/5/",
"/api/v1/studio/6/",
"/api/v1/studio/8/",
"/api/v1/studio/11/",
"/api/v1/studio/12/",
"/api/v1/studio/13/",
"/api/v1/studio/14/",
"/api/v1/studio/15/",
"/api/v1/studio/1/",
"/api/v1/studio/2/"
]
}
}
]
}
我可以使用use_in和Tastypie从列表视图中排除相关字段吗?我可以像这样排除直接资源的字段:
exclude_this_field = fields.CharField(use_in='detail', attribute='exclude_this_field')
State是Studio的ForeignKey字段。如何排除相关资源?
studios = fields.Charfield(use_in='detail', attribute='state__state_id')
我可以制作类似这样的工作来排除相关资源吗?
答案 0 :(得分:0)
如果要隐藏ForeignKeyField的详细信息或列表覆盖资源的init函数,并在调用对象父init后添加use_in值。它应该是这样的:
class YourResource(ModelResource)
...
class Meta:
...
def __init__(self, *args, **kwargs):
# Call the object's parent, which will set up and populate
# the Resource fields from the queryset provided
super(YourResource, self).__init__(*args, **kwargs)
# Now loop through the fields of the resource, and when we
# find the one we only want to be shown in the detail view,
# set its use_in attr appropriately
for field_name, field_object in self.fields.items():
if field_name == 'yourForeignFieldName':
field_object.use_in = 'detail'
我希望这会有所帮助,欢呼!