Search code examples
djangoforeign-keystastypie

Get a single key in place of whole object using tastypie ForeignKey


I'm starting with tastypie, and I'm unable to solve the following problem:

I have a series of models, linked by either ForeignKeys or ManyToMany relationships. I don't want the API to return the whole object, but rather the "id" field only.

As an example, I have the following Taxa model:

class TaxaResource(ModelResource):
class Meta:
    queryset = Taxa.objects.all()
    include_resource_uri = True
    resource_name = 'taxa'

And the Population model:

class PopulationResource(ModelResource):
taxa = fields.ForeignKey(TaxaResource, 'taxa', full=True)
class Meta:
    queryset = Population.objects.all()
    include_resource_uri = True
    resource_name = 'population'

I'd like the taxa field of Population objects to be taxa.id, not the whole taxa object. Any help would be much appreciated...


Solution

  • First, why are you setting full=True?

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

    Setting full=False (the default) will just return the resource URI, and you can get the id out of that.

    There's a bunch of other options.

    1. use taxa = fields.IntegerProperty() in your PopulationResource
    2. in the TaxaResource, specify fields = ['id'] to exclude everything else
    3. replace the dehydrate method in PopulationResource:

    .

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