How do I validate the model attributes with validator based on other field in same model using django ModelSerializer. Example model code:
class LeadSerializer(serializers.ModelSerializer):
class Meta:
model = Lead
fields = (
'name','mobile','email','source',
'referred_by_biz',
'referred_by_ap')
If source entered is 'B', then referred_by_biz'(foreignkey value) cannot be blank and if source is 'A', then 'referred_by_ap' cannot be blank/null (foreignkey). How can I accomplish this at usign validate method? I have just started using REST framework. I am using curl to get the url for the same.
Something like this should probably work :
def validate(self, attrs):
if attrs['source'] == 'A' and attrs['referred_by_ap'] == '':
raise serializers.ValidationError('referred_by_ap cannot be blank')
if attrs['source'] == 'B' and attrs['referred_by_biz'] == '':
raise serializers.ValidationError('referred_by_biz cannot be blank')
return attrs
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.