如何在 django rest 框架的序列化器中添加检查约束验证器?

How to add check constraint validator in serializer in django rest framework?

我有一个模型定义如下:

class Order(models.Model):
    
    qty = models.FloatField() 
    pending_qty = models.FloatField(default=0)

    class Meta:
        constraints = [
            models.CheckConstraint(check=models.Q(
                pending_qty__gte=0), name='pending_qty__gte_0')
        ]

该模型的序列化程序如下:

class NewOrderSz(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = '__all__'

我想在序列化器中添加一个验证器来验证模型中的 'pending_qty__gte_0' CheckConstraint。我该怎么做?

创建实体的视图是:

class NewOrder(generics.CreateAPIView):
    queryset = models.Order.objects.none()
    serializer_class = serializers.NewOrderSz
class NewOrderSz(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = '__all__'

    def validate_pending_qty(self, value):
        if value < 0:
            raise serializers.ValidationError("Pending Qty Less Than Zero!")
        return value

https://www.django-rest-framework.org/api-guide/serializers/#field-level-validation

只需将 pending_qty 定义为 FloatFieldmin_value 约束 你应该没事

class NewOrderSz(serializers.ModelSerializer):
    pending_qty = serializers.FloatField(min_value=0)
    class Meta:
        model = Order
        fields = '__all__'