POST请求上的Django Rest API VIEWSET自定义验证

时间:2018-10-29 10:34:44

标签: django django-rest-framework

我是django rest框架的新手。

这里是model.py

PRICE_CHOICES = (
    ('high','High'),
    ('medium', 'Medium'),
    ('low','Low'),
)
class Book(models.Model):
    price = models.CharField(max_length=255)
    status = models.CharField(max_length=255,choices=PRICE_CHOICES)

我的api views.py:

class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

serializer.py

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ('id', 'price', 'status')

要覆盖价格字段。

2 个答案:

答案 0 :(得分:1)

当价格超过这样的限制时,您可能会引发错误。

 class BookSerializer(serializers.ModelSerializer):
        class Meta:
            model = Book
            fields = ('id', 'price', 'status')

        def validate_price(self, data):
             if data > threshold:
                 raise ValidationError(message='...')
             return data

如果要警告用户,并且要根据其响应做出决定,则需要其他逻辑。您需要在帖子输入中引入新的检查变量/参数。

要每天为用户设置一本书,请在序列化程序中使用覆盖验证方法

class BookSerializer(serializers.ModelSerializer):
        class Meta:
            model = Book
            fields = ('id', 'price', 'status')

        def validate_price(self, data):
             if data > threshold:
                 raise ValidationError(message='...')
             return data
        def validate(self, data):
             # your logic, et user detail and date and check it with db. if found raise exception as shown above.

答案 1 :(得分:1)

U可以通过多种方式使用验证。下面是一个示例

    class BookSerializer(serializers.ModelSerializer):
        class Meta:
            model = Book
            fields = ('id', 'price', 'status')

        def create(self, validated_data):
            # logic for creating object
            # you can extract data from validated_data['name'] and then put your logic
            return validated_data

        def update(self, instance, validated_data):
            # logic for updating object
            return instance