I have two models, one with a foreignkey relationship to the other. I am wanting to be able to create or update multiple entries at the same time. I would not be creating and updating simultaneously.
I keep getting a bit confused about what is going on with people's examples. I was hoping someone could not only show me what I need to do, but also give a bit of an explanation about what is going on at each step. I'm specifically not understanding what the validated_data.get() method is doing, or what exactly is an instance, and what is being done with them.
class ExtraFieldsSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField()
class Meta:
model = ExtraFields
fields = [
'id',
'job',
'custom_data',
]
class JobWriteSerializer(serializers.ModelSerializer):
extra_fields = ExtraFieldsSerializer(many=True)
class Meta:
model = Job
fields = [
"extra_fields",
"custom_data_fields",
]
# Make JobSerializer able to create custom fields.
def create(self, validated_data):
extra_fields = validated_data.pop("extra_fields")
user = User.objects.get(id=self.context['request'].user.id)
client = Client.objects.get(user=self.context['request'].user)
new_job = Job.objects.create(user=user, client=client, **validated_data)
new_job.save()
for field in extra_fields:
new_field = ExtraFields.objects.create(job=new_job, custom_data=field['custom_data'])
new_field.save()
return new_job
# Make JobSerializer able to update custom fields
def update(self, instance, validated_data):
pass