簡體   English   中英

django rest 框架:如何使用相關字段驗證序列化程序中的規則

[英]django rest framework: How to validate a rule in serializers using a related field

我有這些模型:

產品.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)

訂單項.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)

我想在serializers.py驗證order_item.quantity % product_multiple != 0

序列化程序.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

如何在驗證函數中獲取實際的product_multiple

當您進行涉及多個字段的驗證時,您應該使用validate方法,如下所示:

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 value

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM