Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

293
Views
Update Create Method in Django Rest Framework for two nested serializers

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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"}
    ],
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!