I'm trying to create a writeable nested serialiser for my API endpoint, however upon entering my parent serialiser's create
method the nested data doesn't appear in my validated_data
dictionary like it is supposed to in the example here. Instead, the nested key is not even present in the dictionary. Instead, it looks like: {'foo': 'bar'}
. So, the nested keys appear to be flattened, and any other nested object with the same keys are overwritten.
Any clues as to what the problem might be? I have some fairly complicated validation logic, however after trimming all of this out the problem wasn't recitified, so it appears to be irrelevant.
My models are defined thus:
class Payment(models.Model):
id = models.AutoField(primary_key=True)
foo = models.CharField(max_length=15, blank=True, null=True)
class Booking(models.Model):
id = models.AutoField(primary_key=True)
payment = models.ForeignKey(Payment, blank=True, null=True)
My serializers:
class PaymentSerializer(serializers.ModelSerializer):
class Meta:
model = Payment
fields = '__all__'
class BookingSerializer(serializers.ModelSerializer):
payment = PaymentSerializer(source='*', write_only=True)
def create(self, validated_data):
print("Creating booking", validated_data) # Outputs "Creating booking {'foo': 'bar'}"
payment_data = validated_data.pop('payment') # Obviously errors at this point
primary_guest = Payment.objects.create(payment_data)
booking = Booking.objects.create(**validated_data)
# other creation related code
return booking
class Meta:
fields = '__all__'
My ViewSet:
class PrebookingViewSet(viewsets.ModelViewSet):
queryset = Booking.objects.all().order_by('id')
serializer_class = BookingSerializer
My request contains the following POST body:
{
"payment": {
"foo": "bar"
}
}