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

答案是属性 full=True:

成分=田野。ToManyField('mezzanine_recipes.api.IngredientResource', 'ingredients', full=True)

最新更新