简体   繁体   English

基于同一模型中其他字段的REST Django字段验证器

[英]REST django field validator based on other field in same model

How do I validate the model attributes with validator based on other field in same model using django ModelSerializer. 如何使用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). 如果输入的源是“ B”,则referred_by_biz”(外键值)不能为空,如果源是“ A”,则“ referred_by_ap”不能为空/空(外键)。 How can I accomplish this at usign validate method? 如何使用usign validate方法完成此操作? I have just started using REST framework. 我刚刚开始使用REST框架。 I am using curl to get the url for the same. 我正在使用curl获取相同的网址。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM