我从tastypie开始,我无法解决以下问题:
我有一系列模型,由ForeignKeys或ManyToMany关系链接。我不希望API返回整个对象,而只返回“id”字段。
例如,我有以下Taxa
模型:
class TaxaResource(ModelResource):
class Meta:
queryset = Taxa.objects.all()
include_resource_uri = True
resource_name = 'taxa'
Population
模型:
class PopulationResource(ModelResource):
taxa = fields.ForeignKey(TaxaResource, 'taxa', full=True)
class Meta:
queryset = Population.objects.all()
include_resource_uri = True
resource_name = 'population'
我希望taxa
对象的Population
字段为taxa.id
,而不是整个taxa
对象。任何帮助将不胜感激......
答案 0 :(得分:4)
首先,你为什么设置full = True?
taxa = fields.ForeignKey(TaxaResource, 'taxa', full=True)
设置full = False(默认值)只返回资源URI,你可以从中获取id。
还有很多其他选择。
taxa = fields.IntegerProperty()
fields = ['id']
以排除其他所有内容
def dehydrate(self, bundle):
bundle.data['taxa'] = bundle.obj.taxa_id
return bundle