如何在 Django Rest Framework 中使用 ManyToMany 关系与中介模型序列化附加字段?
How to Serialize an additional field using ManyToMany relationship with intermediary model in Django Rest Framework?
我正在尝试通过创建中间模型 IngredientAmount
将字段 amount
添加到 Ingredient
模型中。但是我正在为序列化而苦苦挣扎。
响应应如下所示:
"results": [
......
"ingredients": [
{
"id": 0,
"name": "Potato",
"measurement_unit": "kg",
"amount": 1
}
],
....
]
我正在使用 IngredientAmountSerializer(serializers.ModelSerializer)
,但 Django 说我在 'Ingredient' 对象中并且它没有属性 'amount'.
我做错了什么?
型号
class Ingredient(models.Model):
name = models.CharField(max_length=200)
measurement_unit = models.CharField(max_length=200)
class Meta:
ordering = ['id']
def __str__(self):
return self.name
class IngredientAmount(models.Model):
ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE,
related_name='ingredient_amount')
recipe = models.ForeignKey('Recipe', on_delete=models.CASCADE,
related_name='ingredient_amount')
amount = models.SmallIntegerField(
validators=(
validators.MinValueValidator(
1, 'add amount'),))
class Recipe(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
ingredients = models.ManyToManyField(
Ingredient, through=IngredientAmount,
through_fields=('recipe', 'ingredient', ),
)
tags = models.ManyToManyField(Tag, blank=True, related_name='recipe')
image = models.ImageField()
name = models.CharField(max_length=200)
text = models.TextField()
cooking_time = models.PositiveSmallIntegerField(
validators=(
validators.MinValueValidator(1, message='choose time'),
),
)
序列化程序
class IngredientAmountSerializer(serializers.ModelSerializer):
name = serializers.CharField(source='ingredient.name', read_only=True)
measurement_unit = serializers.IntegerField(source='ingredient.measurement_unit', read_only=True)
class Meta:
model = IngredientAmount
fields = ('id', 'name', 'measurement_unit', 'amount' )
class RecipeSerializer(serializers.ModelSerializer):
author = AuthorSerializer()
tags = TagSerializer(read_only=True, many=True)
image = Base64ImageField(required=True)
ingredients = IngredientAmountSerializer( read_only=True, many=True)
class Meta:
model = Recipe
fields = ('id', 'tags', 'author', 'name', 'image', 'text',
'cooking_time', 'ingredients')
我猜问题是,您正在尝试使用 IngredientAmountSerializer
序列化 Ingredient
模型,而其中 Meta
模型是 IngredientAmount
,而不是 Ingredient
.
更新:如果你想序列化IngredientAmount
,尝试使用source
class RecipeSerializer(serializers.ModelSerializer):
...
ingredients = IngredientAmountSerializer(source='ingredientamount_set', read_only=True, many=True)
我正在尝试通过创建中间模型 IngredientAmount
将字段 amount
添加到 Ingredient
模型中。但是我正在为序列化而苦苦挣扎。
响应应如下所示:
"results": [
......
"ingredients": [
{
"id": 0,
"name": "Potato",
"measurement_unit": "kg",
"amount": 1
}
],
....
]
我正在使用 IngredientAmountSerializer(serializers.ModelSerializer)
,但 Django 说我在 'Ingredient' 对象中并且它没有属性 'amount'.
我做错了什么?
型号
class Ingredient(models.Model):
name = models.CharField(max_length=200)
measurement_unit = models.CharField(max_length=200)
class Meta:
ordering = ['id']
def __str__(self):
return self.name
class IngredientAmount(models.Model):
ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE,
related_name='ingredient_amount')
recipe = models.ForeignKey('Recipe', on_delete=models.CASCADE,
related_name='ingredient_amount')
amount = models.SmallIntegerField(
validators=(
validators.MinValueValidator(
1, 'add amount'),))
class Recipe(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
ingredients = models.ManyToManyField(
Ingredient, through=IngredientAmount,
through_fields=('recipe', 'ingredient', ),
)
tags = models.ManyToManyField(Tag, blank=True, related_name='recipe')
image = models.ImageField()
name = models.CharField(max_length=200)
text = models.TextField()
cooking_time = models.PositiveSmallIntegerField(
validators=(
validators.MinValueValidator(1, message='choose time'),
),
)
序列化程序
class IngredientAmountSerializer(serializers.ModelSerializer):
name = serializers.CharField(source='ingredient.name', read_only=True)
measurement_unit = serializers.IntegerField(source='ingredient.measurement_unit', read_only=True)
class Meta:
model = IngredientAmount
fields = ('id', 'name', 'measurement_unit', 'amount' )
class RecipeSerializer(serializers.ModelSerializer):
author = AuthorSerializer()
tags = TagSerializer(read_only=True, many=True)
image = Base64ImageField(required=True)
ingredients = IngredientAmountSerializer( read_only=True, many=True)
class Meta:
model = Recipe
fields = ('id', 'tags', 'author', 'name', 'image', 'text',
'cooking_time', 'ingredients')
我猜问题是,您正在尝试使用 IngredientAmountSerializer
序列化 Ingredient
模型,而其中 Meta
模型是 IngredientAmount
,而不是 Ingredient
.
更新:如果你想序列化IngredientAmount
,尝试使用source
class RecipeSerializer(serializers.ModelSerializer):
...
ingredients = IngredientAmountSerializer(source='ingredientamount_set', read_only=True, many=True)