2012-11-12 62 views
0

假设以下Resources给出: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',] 

HTTP请求myhost.com/api/v1/recipe/?format=json给出了如下回应:

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

到目前为止好。

但现在,我想用类似的东西交换的成分resource_uri( “/ API/V1 /成份/ 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

答案是属性全= TRUE:

成分= fields.ToManyField( 'mezzanine_recipes.api.IngredientResource',“ingred ients',full = True)

相关问题