【问题标题】:Django Tastypie - How to get related Resources with a single requestDjango Tastypie - 如何通过单个请求获取相关资源
【发布时间】:2012-11-12 15:50:35
【问题描述】:

假设给出以下资源:

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

【问题讨论】:

    标签: django tastypie


    【解决方案1】:

    答案是属性full=True:

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

    【讨论】:

      猜你喜欢
      • 2019-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      • 2013-01-27
      • 1970-01-01
      • 2012-10-15
      相关资源
      最近更新 更多