Django Tastypie - 如何通过单个请求获取相关资源

时间:2012-11-12 15:50:36

标签: django tastypie

假设给出了以下资源:

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',]

对myhost.com/api/v1/recipe/?format=json的HTTP请求给出以下回复:

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

到目前为止一切顺利。

但是现在,我想用这样的东西交换成分resource_uri(“/ api / v1 / ingredient / 1 /”):

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

获得以下回复:

{
    "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",
       }
   ]
}

1 个答案:

答案 0 :(得分:1)

答案是属性full = True:

  

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