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

735
Views
update in serializer: django rest framework

I have a doubt, how to use update() in serializer?

serializers.py

 def update(self, instance, validated_data):
        instance.name = validated_data.get('name', instance.name)
        instance.description = validated_data.get('description', instance.description)
        instance.is_free = validated_data.get('is_free', instance.is_free)
        instance.keyarea = validated_data.get('keyarea', instance.keyarea)
        instance.subject = validated_data.get('subject', instance.subject)

        beneficiary_data = validated_data.get('beneficiary', instance.beneficiary)
        instance.beneficiary.set(*[beneficiary_data])

        section_data = validated_data.get('section', instance.section)
        instance.section.set(*[section_data])

        instance.image = validated_data.get('image', instance.image)
        instance.instructor = validated_data.get('instructor', instance.instructor)
        instance.relevance = validated_data.get('relevance', instance.relevance)
        instance.difficulty = validated_data.get('difficulty', instance.difficulty)
        instance.contributor = validated_data.get('contributor', instance.contributor)
        instance.general_status = validated_data.get('general_status', instance.general_status)
        instance.review_status = validated_data.get('review_status', instance.review_status)

        instance.save()
        return instance


I use a lot of lines here to update the course model, is there any other way to simplify this?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

It's OK generally, but you can do sth like this:

for k, v in validated_data.items():
    setattr(instance, k, v)
over 4 years ago · Santiago Trujillo Report

0

You can also pop the m2m data, then call super().update() and then handle the m2m afterwards like this:

def update(self, instance, validated_data):

    beneficiary_data = validated_data.pop('beneficiary', instance.beneficiary)
    section_data = validated_data.pop('section', instance.section)

    instance = super().update(instance, validated_data)
    instance.beneficiary.set(*[beneficiary_data])
    instance.section.set(*[section_data])

    return instance
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!