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

333
Views
django rest framework create method serializer

I have this working code and I am wondering if the code could be written shorter. Just because I have to specify the agent I am passing each peace of data like below.

class ListingSerializer(serializers.ModelSerializer):

    rooms = serializers.SerializerMethodField()

    def create(self, validated_data):
        agent = self.context.get("agent")
        listing = Listing.objects.create(
            agent=agent,
            title=validated_data["title"],
            description=validated_data["description"],
            floor=validated_data["floor"],
            floor_count=validated_data["floor_count"],
            price=validated_data["price"],
            street=validated_data["street"],
            house_no=validated_data["house_no"],
            door_no=validated_data["door_no"],
            city=validated_data["city"],
            country=validated_data["country"],
            postal_code=validated_data["postal_code"],
            tilstand_report=validated_data["tilstand_report"],
            water_consumption_report=validated_data["water_consumption_report"],
            energy_level_report=validated_data["energy_level_report"],
            property_tax_report=validated_data["property_tax_report"],
        )

        return listing
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can just "inject" the agent in the validated_data:

class ListingSerializer(serializers.ModelSerializer):
    rooms = serializers.SerializerMethodField()

    def create(self, validated_data):
        validated_data['agent'] = self.context['agent']
        return super().create(validated_data)
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!