AttributeError: Получена ошибка AttributeError при попытке получить значение для поля `value` на сериализаторе

Я пытаюсь сериализовать данные в моем проекте электронной коммерции с помощью DRF. Дизайн моей базы данных таков, что у меня есть Product, который может иметь несколько ProductVariant, и каждый ProductVariant может иметь несколько ProductVariantProperty, связанных с ним.

Это мой models.py

class ProductVariantProperty(models.Model):
    name = models.CharField(max_length = 255, null = True, blank = True)

class ProductVariantPropertyValue(models.Model):
    value = models.CharField(max_length = 255, null = True, blank = True)
    property = models.ForeignKey(
        ProductVariantProperty, on_delete = models.CASCADE, null = True, blank = True, related_name = 'product_variant_property_values'
    )

class Product(models.Model):
    name = models.CharField(max_length = 255, unique = True, null = False, blank = False)
    ...

class ProductVariant(models.Model):
    product = models.ForeignKey(
        Product, on_delete = models.CASCADE, null = False, blank = False, related_name = 'product_variants'
    )
    name = models.CharField(max_length = 255, unique = True, null = False, blank = False)
    ...
    properties = models.ManyToManyField(ProductVariantProperty, blank = True, related_name = 'product_variants')
   

Это тело моего запроса

{
    "name": "Product 1",
    ...
    "product_variants": [
        {
            "name": "Example Variant 1",
            ...
            "properties": [
                {
                    "name": "color",
                    "value": "blue"
                },
                {
                    "name": "size",
                    "value": "large"
                }
            ]
        },
        {...}
    ]
}

Вот ошибка, которую я получил при попытке сериализации.

AttributeError: Got AttributeError when attempting to get a value for field `value` on serializer `ProductVariantPropertyValueSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `ProductVariantProperty` instance.
Original exception text was: 'ProductVariantProperty' object has no attribute 'value'.

То, что я пробовал, находится здесь: views.py

class ProductAPIView(generics.GenericAPIView):
    def post(self, request):
        serializer = self.serializer_class(data = request.data)
        product_variant_serializer = ProductVariantSerializer(data = request.data.get("product_variants"), many = True)
        
        if serializer.is_valid() and product_variant_serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status = status.HTTP_201_CREATED)
        
        return Response(
            serializer.errors or product_variant_serializer.errors, 
            status = status.HTTP_400_BAD_REQUEST
        )

serializers.py

class ProductVariantPropertyValueSerializer(serializers.ModelSerializer):
    name = serializers.CharField(source="product_variant_property_values.name", min_length=1, max_length=255)
    value = serializers.CharField(min_length = 1, max_length = 255)

    class Meta:
        model = ProductVariantPropertyValue
        fields = ['name', 'value']

class ProductVariantSerializer(serializers.ModelSerializer):
    name = serializers.CharField(min_length = 1, max_length = 255)
    ...
    properties = ProductVariantPropertyValueSerializer(many = True)

    class Meta:
        model = ProductVariant
        fields = [
            'id', 'name', ..., 'properties'
        ]

class ProductSerializer(serializers.ModelSerializer):
    name = serializers.CharField(min_length = 1, max_length = 255)
    ...
    product_variants = ProductVariantSerializer(many = True)

    class Meta:
        model = Product
        fields = [
            'id', 'name', ... ,'product_variants'
        ]

    def create(self, validated_data):
        try:
            variants_data = validated_data.pop('product_variants')
            product = Product.objects.create(**validated_data)

            variants_instances = []
            for variant_data in variants_data:
                properties_data = variant_data.pop('properties', [])
                variant_instance = ProductVariant.objects.create(product=product, **variant_data)
                variants_instances.append(variant_instance)

                # print(properties_data)
                for property_data in properties_data:
                    property_name = property_data['product_variant_property_values']['name']
                    property_value = property_data['value']
                    
                    property_instance, _ = ProductVariantProperty.objects.get_or_create(name = property_name)
                    ProductVariantPropertyValue.objects.create(property = property_instance, value = property_value)

                    # This line is where i am getting the problem
                    variant_instance.properties.add(property_instance)

            return product
        
        except Exception as e:
            return e
Вернуться на верх