当我尝试更新或发布新实例时,我的部分数据消失了。
使用这样的数据
data = {
'item': 'Product',
'station': 'Workbench',
'ingredients':[
{'item': 'ing1', 'amount': 2},
{'item': 'ing2', 'amount':1}
]
}
我有一个带有嵌套序列化程序的序列化程序,可根据需要get_or_creates成分。
class IngredientSerializer(serializers.ModelSerializer):
class Meta:
model = Ingredient
fields = ('item', 'amount')
class WriteableRecipeSerializer(serializers.ModelSerializer):
item = serializers.PrimaryKeyRelatedField(queryset=Item.objects.all())
ingredients = IngredientSerializer(many=True)
station = serializers.PrimaryKeyRelatedField(queryset=Item.objects.all())
def create(self, validated_data):
logger.info(validated_data)
ingredient_data = validated_data.pop('ingredients')
recipe = Recipe.objects.create(**validated_data)
for ingredient in ingredient_data:
ingredient_item = Item.objects.get(name=ingredient['item'])
amount = ingredient['amount']
ingredient, created = Ingredient.objects.get_or_create(item=ingredient_item, amount=amount
)
recipe.ingredients.add(ingredient)
return recipe
def update(self, instance, validated_data):
logger.info(validated_data)
ingredient_data = validated_data.pop('ingredients')
instance.item = validated_data.get('item', instance.item)
instance.station = validated_data.get('station', instance.station)
for ingredient in ingredient_data:
ingredient_item = Item.objects.get(name=ingredient['item'])
amount = ingredient['amount']
ingredient, created = Ingredient.objects.get_or_create(item=ingredient_item, amount=amount)
logger.info('Itering')
instance.ingredients.add(ingredient)
return instance
class Meta:
model = Recipe
fields = ('item', 'amount', 'ingredients', 'station')
数据验证并得到响应代码200,但我的记录器在create和update方法中显示的响应数据和validated_data都返回如下内容:
data = {
'item': 'Product',
'station': 'Workbench',
'ingredients':[]
}
成分数据在某个地方AWOL。 我已经尝试将Ingredient Serializer作为通用序列化程序,并重写WriteableRecipeSerializer的验证,只是返回attrs但问题仍然存在。
编辑模型:
class Ingredient(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
amount = models.IntegerField()
def __str__(self):
return self.item.name + '(' + str(self.amount) + ')'
class Recipe(models.Model):
item = models.OneToOneField(Item, related_name='recipe', on_delete=models.CASCADE)
amount = models.IntegerField(default=1)
ingredients = models.ManyToManyField(Ingredient)
station = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='as_station')
def __str__(self):
return 'Recipe: ' + str(self.item)