drf-writable-nested icon indicating copy to clipboard operation
drf-writable-nested copied to clipboard

Problem of pass through values to nested serializers from the call to the base serializer's save method.

Open playma opened this issue 2 years ago • 3 comments

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

playma avatar Jul 28 '23 01:07 playma

Use field_name instead of field.source?

https://github.com/beda-software/drf-writable-nested/blob/master/drf_writable_nested/mixins.py#L32-L52

playma avatar Jul 28 '23 02:07 playma

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?

ruscoder avatar Oct 31 '23 22:10 ruscoder

@playma I've reviewed your PR, indeed, it makes sense to check field_name in validated_data instead of field.source.

ruscoder avatar Oct 31 '23 22:10 ruscoder