Reputation: 773
I have a POST function like this:
def post(self, request):
try:
serializer = CCTDSPostSerializer(data=request.data)
print("serializer", serializer)
print("is valid", serializer.is_valid())
The Serializer is as follows, its not a model serializer for specific reasons.
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
The data that I am passing it is:
{
"tds_id":[1],
"status":"closed",
"transaction":"ABC",
"comment":"Boom"
}
Now based on the conditions on the data present in the database, it comes to the statement print("returning false")
i.e. it is returning False
, but on the view side, the statement serializer.is_valid()
gives the output as True
How come the validate function returns False and the is_valid
returns True
?
Upvotes: 0
Views: 739
Reputation: 47374
validate
method returns validated date or raise error. Since your validate
method doesnt raise any error is_valid()
returns True
. Change method like this to fix:
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")
Upvotes: 2