Prometheus
Prometheus

Reputation: 33595

Django reverse lookup in API

I would like to know how I have get a list of all related animals in my TastyPie api/houses call:

For example:

House Model:

class House(models.Model):
    description = models.CharField(max_length=250, blank=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL)

Each house can have one or more of the following:

class Dog(models.Model):
      name = models.CharField(max_length=250)
      house = models.ForeignKey(House, null=True)

class Cat(models.Model):
      name = models.CharField(max_length=250)
      house = models.ForeignKey(House, null=True)

class Hamster(models.Model):
      name = models.CharField(max_length=250)
      house = models.ForeignKey(House, null=True)

class Fish(models.Model):
      name = models.CharField(max_length=250)
      house = models.ForeignKey(House, null=True)

This returns:

[
{
id: 1,
description: "Test Offer22",
user: {
date_joined: "2014-01-02T18:39:40",
email: "[email protected]",
id: 1,
is_active: true,
last_login: "2014-01-05T15:44:30"
}
},

I would like in this JSON to also see a list of all animals that are related to the house i.e. cat, dog. Can this be done in Tastypie? I have read about Lookups that span relationships is this what I'm after here? I don't really understand how you get a relationship from the 'wrong' side, if you know that I mean

Upvotes: 0

Views: 62

Answers (1)

sk1p
sk1p

Reputation: 6735

I think you are looking for the full=True argument for your related fields. For example:

class HouseResource(ModelResource):
    dogs = fields.ToManyField('DogResource', 'dog_set', full=True)

Upvotes: 1

Related Questions