Django序列化程序验证不触发

时间:2018-04-09 14:43:16

标签: python django

我在Django模型上有一个选择字段:

VALID = 0
INVALID = 1
FLANGGED = 2
NOT_REVIEWED = 3

STATUS_CHOICES = (
    (VALID, 'Valid'),
    (INVALID, 'Invalid'),
    (FLANGGED, 'Flagged'),
    (NOT_REVIEWED, 'Not Reviewed'),
)

review_status = models.PositiveSmallIntegerField(
    choices=STATUS_CHOICES, default=NOT_REVIEWED)

当我将其显示到前端时,我使用obj.get_review_status_display()来获取字符串值。

当我编辑此模型(通过DRF),并且我传递整数值时,我可以看到我的序列化器上的validate()方法被调用。但是,当我传递字符串值来修补模型时,validate()永远不会被调用:

def validate(self, data):
    valid_status_key = False
    if 'review_status' in data:
        for k, v in Application.STATUS_CHOICES:
            if v == data['review_status']:
                valid_status_key = k

        if not valid_status_key:
            raise serializers.ValidationError('Invalid review status')
        else:
            data['review_status'] = valid_status_key

    # only called when data['review_statuse'] is an Int, not String
    assert False, [data, valid_status_key]

    return data

那么......我如何将String值传递给后端,并点击validate()方法根据我的Choices字段验证它?

0 个答案:

没有答案