gpt4 book ai didi

python - 如何编写基于类的 Django 验证器?

转载 作者:太空狗 更新时间:2023-10-30 01:07:16 25 4
gpt4 key购买 nike

我正在使用 Django 1.8。

documentation on writing validators有一个基于函数的验证器的例子。它还说明了以下关于使用类的内容:

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__() 有什么用,如何使用?

一个例子会很有帮助。完整的答案也可能值得提交到官方文档中。

谢谢!

最佳答案

验证器函数的一大优势是它们非常简单。它们只是将一个值作为参数,检查它是否有效,如果无效则抛出 ValidationError。您无需担心 deconstruct__eq__ 方法来使迁移工作。

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

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

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

关于python - 如何编写基于类的 Django 验证器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32139000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com