2015-12-25 64 views
2

我遇到問題。我正在用Django REST框架創建一個API,並且我創建了序列化程序來返回食譜和配料來烹飪它。序列化程序正在返回「模型對象」而不是特定字段

models.py:

class Recipes(models.Model): 
     title = models.CharField(max_length=50,null=True, blank=False, verbose_name=('name')) 

class Tag(models.Model): 
     name = models.CharField(max_length=50,null=True, blank=False, verbose_name=('name')) 

class ListTag(models.Model): 
     recipes = models.ForeignKey(Recipes, blank=False, on_delete=models.CASCADE, related_name='recipes') 
     tag = models.ForeignKey(Tag, blank=False, on_delete=models.CASCADE, related_name='tag') 

我有類RecipesTag(成分)和ListTag是包含與收到的ID每種成分列表。

serializers.py

class RecipesSerializer(serializers.ModelSerializer): 
    ingredient = serializers.StringRelatedField(many=True, read_only=True, source='recipes') 
    class Meta: 
     model = Recipes 
     fields = ('title', 'ingredient') 

class TagSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Tag 

class ListTagSerializer(serializers.ModelSerializer): 
    tag = serializers.SlugRelatedField(
     read_only=True, 
     slug_field='name' 
    ) 
    class Meta: 
     model = ListeTag 
     fields = ('recipes','tag') 

結果

對於RecipesSerializer

{ 
    "title": "Pancakes à la canadienne", 
    "ingredient": [ 
     "ListTag object", 
     "ListTag object", 
     "ListTag object" 
    ] 
} 

但我想

{ 
    "title": "Pancakes à la canadienne", 
    "ingredient": [ 
     { 
      "id": 2, 
      "name": "milk" 
     }, 
     { 
      "id": 3, 
      "name": "rice" 
     }, 
     { 
      "id": 4, 
      "name": "salade" 
     }, 
     { 
      "id": 5, 
      "name": "tomato" 
     } 
    ] 
} 

{ 
    "title": "Pancakes à la canadienne", 
    "ingredient": ["milk","rice","salade","tomato"] 
} 
+0

剛擡起頭,你的'ListTag'模型創建的蠻力方式Django中的多對多關係。您可以在'Recipes'和'Tag'之間使用'ManyToMany'字段來獲得相似的結果。 –

回答

1

您可以通過使用像嵌套關係,做到這一點:

class RecipesSerializer(serializers.ModelSerializer): 
    recipes = ListTagSerializer(many=True,read_only=True) 
    class Meta: 
     model = Recipes 
     fields = ('title', 'recipes') 

class ListTagSerializer(serializers.ModelSerializer): 
    id = serializers.ReadOnlyField(source='tag.id') 
    tag = serializers.SlugRelatedField(
     read_only=True, 
     slug_field='name' 
    ) 
    class Meta: 
     model = ListeTag 
     fields = ('id','tag') 

詳細瞭解嵌套關係here

+0

非常感謝。它的作品完美:) – Mnvxmanu

相關問題