Issue
I have these models:
product.py
class Product(models.Model):
product_title = models.CharField(max_length=100)
product_price = models.DecimalField(max_digits=12, decimal_places=2)
product_multiple = models.PositiveIntegerField(blank=True, null=True)
order_item.py
class OrderItem(models.Model)
order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items', null=True, blank=True)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
price = models.FloatField(default=0)
quantity = models.BigIntegerField(default=1)
profitability = models.CharField(max_length=50, null=True, blank=True)
I want to validate in serializers.py
if the order_item.quantity % product_multiple != 0
serializers.py
class OrderItemSerializer(serializers.ModelSerializer):
class Meta:
model = OrderItem
fields = ('id', 'order', 'product', 'price',
'quantity', 'profitability')
def validate_quantity(self, value):
data = self.get_initial()
quantity = data.get("quantity")
# This is where the `product.product_multiple` value is needed
if int(quantity) % product.product_multiple != 0:
raise serializers.ValidationError("Quantity is not multiple")
return value
How can I get the actual product_multiple
inside the validate function?
Solution
As you are doing a validation that involves multiple fields, you should use the validate method as follows:
def validate(self, data):
quantity = data.get('quantity')
product = data.get('product')
if int(quantity) % product.product_multiple != 0:
raise serializers.ValidationError("Quantity is not multiple")
return data
Answered By - Ozgur Akcali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.