英文:
Validate field input using django serializer
问题
我有一个Django模型中的字段code。
我需要检查输入字符串是否具有以下属性:
- 长度应为5个字符
 - 第1和第2个字符应为字母
 - 第3和第4个字符应为数字
 - 第5个字符应为E或N
 
我有一个如下所示的序列化器,满足第一个条件。
class MyModelSerializer(serializers.ModelSerializer):
    code = serializers.CharField(max_length=5, min_length=5)
    class Meta:
        model = MyModel
        fields = '__all__';
如何满足剩余条件?
英文:
I have a field code in my Django model.
I have to check if the input string has the following properties:
- Length should be 5 characters
 - 1st & 2nd characters should be alphabets
 - 3rd & 4th characters should be numbers
 - 5th character should be E or N
 
I have a serializer as shown below which satisfies the first condition.
class MyModelSerializer(serializers.ModelSerializer):
    code = serializers.CharField(max_length=5, min_length=5)
    class Meta:
        model = MyModel
        fields = '__all__'
How can I fulfil the remaining conditions?
答案1
得分: 1
以下是翻译好的部分:
"validate_code"函数的名称在序列化器中不是强制的。你可以根据喜好命名它,只要以单词"validate"开头并接受一个值参数。值参数代表正在验证的字段的值。
下面是关于上面使用的正则表达式模式的一些深入信息。
第1和第2个字符应为字母:
[A-Za-z]{2} 匹配任意两个字母字符,确保第一个和第二个字符为字母。
第3和第4个字符应为数字:
\d{2} 匹配任意两个数字字符,确保第三和第四个字符为数字。
第5个字符应为E或N:
[EN] 匹配E或N中的任何一个,确保第五个字符为E或N。
英文:
The remaining conditions can be fulfilled by adding a custom validator and using regex.
import re
class MyModelSerializer(serializers.ModelSerializer):
    code = serializers.CharField(max_length=5, min_length=5)
    def validate_code(self, value):
        # check if the code matches the required pattern
        pattern = r'^[A-Za-z]{2}\d{2}[EN]$'
        if not re.match(pattern, value):
            raise serializers.ValidationError('Code does not match required format')
        return value
The name of the function validate_code is not mandatory in the serializer. You can name it whatever you like, as long as it starts with the word "validate" and takes in a value argument. The value argument represents the value of the field being validated.
Here is a bit of in-depth info about the regex pattern used above.
1st & 2nd characters should be alphabets:
[A-Za-z]{2} matches any two alphabetical characters, ensuring that the first and second characters are alphabet
3rd & 4th characters should be numbers:
\d{2} matches any two numeric characters, ensuring that the third and fourth characters are numbers
5th character should be E or N:
[EN] matches either E or N, ensuring that the fifth character is either E or N
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论