如何编写基于类的Django验证程序? [英] How do I write a Class-Based Django Validator?

查看:48
本文介绍了如何编写基于类的Django验证程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django 1.8.

I'm using Django 1.8.

有关编写验证器的文档的示例基于功能的验证器.在使用类时,还会显示以下内容:

The documentation on writing validators has an example of a function-based validator. It also says the following on using a class:

对于更复杂或可配置的验证器,您也可以将类与 __ call __()方法一起使用.例如,RegexValidator使用此技术.如果在验证器模型字段选项中使用了基于类的验证器,则应通过添加 deconstruct() __ eq __()方法来确保其可被迁移框架序列化

You can also use a class with a __call__() method for more complex or configurable validators. RegexValidator, for example, uses this technique. If a class-based validator is used in the validators model field option, you should make sure it is serializable by the migration framework by adding deconstruct() and __eq__() methods.

  • 与基于函数的验证器相比,基于类的优点/缺点是什么?
  • __ call __()的用途是什么?
  • deconstruct()的用途是什么?
  • __ eq __()的用途是什么?
    • What are the pros/cons of class-based against function-based validators?
    • What is __call__() used for, and how is it used?
    • What is deconstruct() used for, and how is it used?
    • What is __eq__() used for, and how is it used?
    • 一个例子会有所帮助.完整答案也可能值得在正式文档中提交.

      An example would be helpful. A full answer may also be worth submitting to be in the official documentation.

      谢谢!

      推荐答案

      验证器功能的一大优点是它们确实很简单.他们只是将一个值用作参数,检查其是否有效,如果无效,则引发 ValidationError .您不必担心 deconstruct __ eq __ 使迁移正常进行的方法.

      A big advantage of validator functions is that they are really simple. They simply take one value as an argument, check that it's valid, and and raise ValidationError if it's not. You don't need to worry about deconstruct and __eq__ methods to make migrations work.

      文档中的 validate_even 示例比验证器类要简单得多.

      The validate_even example in the docs is much simpler than a validator class would be.

      def validate_even(value):
          if value % 2 != 0:
              raise ValidationError('%s is not an even number' % value)
      

      如果您还需要通过其他数字检查可除性,则值得创建一个验证器类 ValidateDivisibleBy .然后,您可以使用 ValidateDivisibleBy(2) ValidateDivisibleBy(3)等.但是很多时候,验证器功能就足够了.

      If you need to check divisibility by other numbers as well, then it would be worth creating a validator class ValidateDivisibleBy. Then you could use ValidateDivisibleBy(2), ValidateDivisibleBy(3) and so on. But a lot of the time, a validator function is good enough.

      这篇关于如何编写基于类的Django验证程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆