Django序列化器的is_valid返回True,即使validate返回False

时间:2018-09-29 16:19:05

标签: python django python-3.x django-rest-framework

我有这样的POST功能:

SimpleStackView

Serializer如下,出于特定原因,它不是模型序列器。

    def post(self, request):
    try:

        serializer = CCTDSPostSerializer(data=request.data)
        print("serializer", serializer)
        print("is valid", serializer.is_valid())

我要传递的数据是:

class CCTDSPostSerializer(serializers.Serializer):
status = serializers.CharField()
transaction = serializers.CharField(allow_blank=True, allow_null=True)
comment = serializers.CharField(allow_blank=True, allow_null=True)
tds_id = serializers.ListField(child=serializers.IntegerField())

def check_tds_eligibility(self, data):
    tds_ids = data.get('tds_id', None)

    if tds_ids is not None:
        tds_obj = TDS.objects.filter(id__in=tds_ids, status='open')
        if tds_obj.count() == len(tds_ids):
            return tds_ids
    return None

def validate_status_transaction(self, obj):
    status = obj.get('status', None)
    transaction = obj.get('transaction', None)

    if status == 'closed' and transaction is not None:
        return True
    elif status == 'rejected' and transaction is None:
        return True
    return False

def validate(self, obj):
    validate_status_transaction = self.validate_status_transaction(obj)
    tds_ids = self.check_tds_eligibility(obj)
    if validate_status_transaction and tds_ids:
        print("returning obj")
        return obj
    print("returning false")
    return False

现在,基于数据库中存在的数据的条件,它进入语句{ "tds_id":[1], "status":"closed", "transaction":"ABC", "comment":"Boom" } ,即返回print("returning false"),但是在视图方面,语句False给出了输出为serializer.is_valid()

validate函数为什么返回False,而True返回is_valid

1 个答案:

答案 0 :(得分:2)

validate方法返回有效日期或引发错误。由于您的validate方法不会引发任何错误,因此is_valid()返回True。像这样更改方法即可解决:

def validate(self, obj):
    validate_status_transaction = self.validate_status_transaction(obj)
    tds_ids = self.check_tds_eligibility(obj)
    if validate_status_transaction and tds_ids:
        print("returning obj")
        return obj
    print("returning false")
    raise serializers.ValidationError("Some error")