使用tastypie ForeignKey获取单个密钥来代替整个对象

时间:2013-12-05 22:46:11

标签: django foreign-keys tastypie

我从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对象。任何帮助将不胜感激......

1 个答案:

答案 0 :(得分:4)

首先,你为什么设置full = True?

taxa = fields.ForeignKey(TaxaResource, 'taxa', full=True)

设置full = False(默认值)只返回资源URI,你可以从中获取id。

还有很多其他选择。

  1. 在您的PopulationResource中使用taxa = fields.IntegerProperty()
  2. TaxaResource中的
  3. ,指定fields = ['id']以排除其他所有内容
  4. 替换PopulationResource中的脱水方法:
  5. def dehydrate(self, bundle):
        bundle.data['taxa'] = bundle.obj.taxa_id
        return bundle