Django validator

Django validator

Django can be used to re-verification, judgment logic functions

validators

  • UniqueValidator
    • This verification can be used to model unique = True fields enforcing the constraints. It takes a required parameter and an optional parameter messages:
      • queryset required - this is supposed to enforce the uniqueness of the query set.
      • message - Error message used when authentication fails.
      • lookup - Find in a conventional example has a verification value. The default is 'exact'.
        This should be applied validator serializer field as follows:
        validators = [UniqueValidator (BlogPost.objects.all QuerySet = ())]
  • UniqueTogetherValidator
    • This procedure can be used to validate the model unique_together example for enforcing the constraints. It has two required parameters and one optional parameter messages:
      • queryset required - this is supposed to enforce the uniqueness of the query set.
      • fields required - should create a unique list of field names or tuple sets. These must be present as a sequence of classes field.
      • message - Error message used when authentication fails.

      class TaskSerializer(serializers.ModelSerializer):
      class Meta:
      model = Task
      fields = ('name', 'keyword', 'user_id')

          validators = [
              UniqueTogetherValidator(
                  queryset=Task.all(),
                  fields=['user_id', 'name'],
                  message='相同任务名已存在'
              ),
              UniqueTogetherValidator(
                  queryset=Task.all(),
                  fields=['user_id', 'keyword'],
                  message='相同关键字已存在'
              ),
          ]

Optional field

By default, "with only" verification is mandatory for all the fields required = True. In some cases, you may want to explicitly required = False applied to one of the fields, in this case, the required verification of behavior is not clear.

In this case, you typically excluded from verification program sequence of classes, but in .validate () method or explicitly written in the view of any validation logic.

E.g:

class BillingRecordSerializer(serializers.ModelSerializer):
    def validate(self, data):
        # Apply custom validation either here, or in the view.

    class Meta:
        fields = ['client', 'date', 'amount']
        extra_kwargs = {'client': {'required': False}}
        validators = []  # Remove a default "unique together" constraint.

Custom validator

def judge(aaa):
    if len(aaa) != 40:
        print('长度不正确')
        return

  
  
from xxx import judge
validators = 

Guess you like

Origin www.cnblogs.com/liuhuan086/p/11896970.html