serialization - Django REST Framework, PUT/POST serializer data disappearing -
i having trouble part of data disappearing when try update or post new instance.
with data this
data = { 'item': 'product', 'station': 'workbench', 'ingredients':[ {'item': 'ing1', 'amount': 2}, {'item': 'ing2', 'amount':1} ] }
i have serializer nested serializer get_or_creates ingredients needed.
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) 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) 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')
the data validates , response code 200, both response data , validated_data shown logger in create , update methods return this:
data = { 'item': 'product', 'station': 'workbench', 'ingredients':[] }
the ingredients data going awol somewhere. have tried making ingredient serializer generic serializer overriding writeablerecipeserializer's validation return attrs problem persists.
edit models:
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)
Comments
Post a Comment