【问题标题】:Get a single key in place of whole object using tastypie ForeignKey使用 sweetpie ForeignKey 获取单个键来代替整个对象
【发布时间】:2013-12-23 02:58:15
【问题描述】:

我是从 sweetpie 开始的,但我无法解决以下问题:

我有一系列模型,通过 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'

我希望Population 对象的taxa 字段是taxa.id,而不是整个taxa 对象。任何帮助将不胜感激...

【问题讨论】:

    标签: django foreign-keys tastypie


    【解决方案1】:

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

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

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

    还有很多其他选择。

    1. 在您的 PopulationResource 中使用 taxa = fields.IntegerProperty()
    2. 在 TaxaResource 中,指定 fields = ['id'] 以排除其他所有内容
    3. 替换 PopulationResource 中的 dehydrate 方法:

    .

    def dehydrate(self, bundle):
        bundle.data['taxa'] = bundle.obj.taxa_id
        return bundle
    

    【讨论】:

      猜你喜欢
      • 2012-07-29
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-17
      • 1970-01-01
      相关资源
      最近更新 更多