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')
我有類Recipes
,Tag
(成分)和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"]
}
剛擡起頭,你的'ListTag'模型創建的蠻力方式Django中的多對多關係。您可以在'Recipes'和'Tag'之間使用'ManyToMany'字段來獲得相似的結果。 –