Problem of pass through values to nested serializers from the call to the base serializer's save method.
I want to pass values to nested serializers that have changed names, but it seems not to work. Can somebody help me?
Serializer
class PriceSerializer(PriceBaseSerializer):
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['id', 'merchant', 'name', 'description', 'images', 'metadata', 'is_livemode']
extra_kwargs = {
'is_livemode': {'required': False},
'merchant': {'required': False},
}
product_data = ProductSerializer(source='product', required=False)
def validate(self, attrs):
if not attrs.get('product') and not attrs.get('product_data'):
raise serializers.ValidationError('product or product_data is required')
return attrs
class Meta:
model = Price
fields = [
'id',
'merchant',
'product',
'product_data',
'currency',
'unit_amount',
'metadata',
'is_livemode',
'payment_link_count',
]
read_only_fields = ['payment_link_count']
extra_kwargs = {
'product': {'required': False},
'is_livemode': {'required': False},
'merchant': {'required': False},
}
Save function 1
serializer.save(
product_data={
'merchant_id': self.merchant_id,
'is_livemode': self.is_livemode,
},
merchant_id=self.merchant_id,
is_livemode=self.is_livemode,
)
Error happens 1
TypeError: Price() got an unexpected keyword argument 'product_data'
Save function 2
serializer.save(
product={
'merchant_id': self.merchant_id,
'is_livemode': self.is_livemode,
},
merchant_id=self.merchant_id,
is_livemode=self.is_livemode,
)
Error happens 2 (Not pass value successfully)
django.db.utils.IntegrityError: null value in column "is_livemode" of relation "billing_product" violates not-null constraint
Use field_name instead of field.source?
https://github.com/beda-software/drf-writable-nested/blob/master/drf_writable_nested/mixins.py#L32-L52
Hi @playma! There was a similar issue #22 that was fixed a long time ago and also covered with tests. I really surprised that it does not work in your case. Could you please share a piece of your code of PriceBaseSerializer where drf-writable-nested actually mixed?
@playma I've reviewed your PR, indeed, it makes sense to check field_name in validated_data instead of field.source.