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
CodePudding user response:
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)