Issue
I've found many answers to similar questions but not to my specific one. I'm trying to update the Create Method for my serializer which has two nested serializers:
class TaskSerializer(serializers.ModelSerializer):
products = ProductSerializer()
prep = PrepSerializer()
class Meta:
model = Task
fields = '__all__'
def create(self, validated_data):
products_data = validated_data.pop('products')
task = Task.objects.create(**validated_data)
for products_data in products_data:
Product.objects.create(task=task, **products_data)
return task
I want to add the "prep" nested serializer in as well to be updated at the same time but I can't seem get the syntax right.
Any help, greatly appreciated.
Solution
It should work fine, I think you are missing many=True
. Does this work? (Assuming and products
and prep
should be many)
And also assuming that your models are structured like this:
class Task(models.Model)
#fields
class Product(models.Model)
task = models.ForeignKey(Task, on_delete=models.CASCADE)
class Prep(models.Model)
task = models.ForeignKey(Task, on_delete=models.CASCADE)
class TaskSerializer(serializers.ModelSerializer):
products = ProductSerializer(many=True)
preps = PrepSerializer(many=True)
class Meta:
model = Task
fields = '__all__'
def create(self, validated_data):
products_data = validated_data.pop('products')
preps_data = validated_data.pop('preps')
task = Task.objects.create(**validated_data)
for products_data in products_data:
Product.objects.create(task=task, **products_data)
for prep_data in preps_data:
Prep.objects.create(task=task, **prep_data)
return task
Then you can send a request like:
{
"products": [
{"foo": "bar"}
],
"preps": [
{"foo": "bar"}
],
}
Answered By - Felix Eklöf
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.