Search code examples
djangotastypie

Django Tastypie - How to get related Resources with a single request


Suppose following Resources are given:

class RecipeResource(ModelResource):
    ingredients = fields.ToManyField(IngredientResource, 'ingredients')

    class Meta:
        queryset = Recipe.objects.all()
        resource_name = "recipe"
        fields = ['id', 'title', 'description',]


class IngredientResource(ModelResource):
    recipe = fields.ToOneField(RecipeResource, 'recipe')

    class Meta:
        queryset = Ingredient.objects.all()
        resource_name = "ingredient"
        fields = ['id', 'ingredient',]

A HTTP Request to myhost.com/api/v1/recipe/?format=json gives following response:

{
    "meta":
    {
        ...
    },
    "objects":
    [
       {
           "description": "Some Description",
           "id": "1",
           "ingredients":
           [
               "/api/v1/ingredient/1/"
           ],
           "resource_uri": "/api/v1/recipe/11/",
           "title": "MyRecipe",
       }
   ]
}

So far so good.

But now, I would like to exchange the ingredients resource_uri ("/api/v1/ingredient/1/") with something like that:

{
   "id": "1",
   "ingredient": "Garlic",
   "recipe": "/api/v1/recipe/1/",
   "resource_uri": "/api/v1/ingredient/1/",
}

To get following response:

{
    "meta":
    {
        ...
    },
    "objects":
    [
       {
           "description": "Some Description",
           "id": "1",
           "ingredients":
           [
               {
                   "id": "1",
                   "ingredient": "Garlic",
                   "recipe": "/api/v1/recipe/1/",
                   "resource_uri": "/api/v1/ingredient/1/",
               }
           ],
           "resource_uri": "/api/v1/recipe/11/",
           "title": "MyRecipe",
       }
   ]
}

Solution

  • The answer is the attribute full=True:

    ingredients = fields.ToManyField('mezzanine_recipes.api.IngredientResource', 'ingredients', full=True)