class BooleanField(Field):
empty_strings_allowed = False
default_error_messages = {
'invalid': _(u"'%s' value must be either True or False."),
}
description = _("Boolean (Either True or False)") def __init__(self, *args, **kwargs):
kwargs['blank'] = True
if 'default' not in kwargs and not kwargs.get('null'):
kwargs['default'] = False
Field.__init__(self, *args, **kwargs) def get_internal_type(self):
return "BooleanField" def to_python(self, value):
if value in (True, False):
# if value is 1 or 0 than it's equal to True or False, but we want
# to return a true bool for semantic reasons.
return bool(value)
if value in ('t', 'True', ''):
return True
if value in ('f', 'False', ''):
return False
msg = self.error_messages['invalid'] % str(value)
raise exceptions.ValidationError(msg) def get_prep_lookup(self, lookup_type, value):
# Special-case handling for filters coming from a Web request (e.g. the
# admin interface). Only works for scalar values (not lists). If you're
# passing in a list, you might as well make things the right type when
# constructing the list.
if value in ('', ''):
value = bool(int(value))
return super(BooleanField, self).get_prep_lookup(lookup_type, value) def get_prep_value(self, value):
if value is None:
return None
return bool(value) def formfield(self, **kwargs):
# Unlike most fields, BooleanField figures out include_blank from
# self.null instead of self.blank.
if self.choices:
include_blank = (self.null or
not (self.has_default() or 'initial' in kwargs))
defaults = {'choices': self.get_choices(
include_blank=include_blank)}
else:
defaults = {'form_class': forms.BooleanField}
defaults.update(kwargs)
return super(BooleanField, self).formfield(**defaults)

看起来,BooleanField 要比复杂的多,我们只分析其中的

to_python 函数

     def to_python(self, value):
if value in (True, False):
# if value is 1 or 0 than it's equal to True or False, but we want
# to return a true bool for semantic reasons.
return bool(value)
if value in ('t', 'True', ''):
return True
if value in ('f', 'False', ''):
return False
msg = self.error_messages['invalid'] % str(value)
raise exceptions.ValidationError(msg)

函数获得一个参数value,判断value是不是 (True,False,1, 0)中的一个,如果是,返回True或False。

下面同理,在value是字符串的情况下,判断value的值  是不是 ('t', 'True', '1') 中的一个,是则返回 True...

如果执行到msg = XXXXX 这里,就说明 to_python执行失败了,返回错误...抛出异常...


需要注意的是:

>>> a = True
>>> b = False
>>> c = 1
>>> d = 0
>>> e = 11
>>> f = -1
>>> a in (True,False)
True
>>> b in (True,False)
True
>>> c in (True,False)
True
>>> d in (True,False)
True
>>> e in (True,False)
False
>>> f in (True,False)
False
>>>

如果一个大于1的数,是不会 in (True,False) 中的,这和我们平时使用

>>> if 11:
print 'aa' aa
>>>

是不同的。

django源码解析之 BooleanField (二)的更多相关文章

  1. django源码解析之 BooleanField (三)

    def __init__(self, *args, **kwargs): kwargs['blank'] = True if 'default' not in kwargs and not kwarg ...

  2. 【原】Android热更新开源项目Tinker源码解析系列之二:资源文件热更新

    上一篇文章介绍了Dex文件的热更新流程,本文将会分析Tinker中对资源文件的热更新流程. 同Dex,资源文件的热更新同样包括三个部分:资源补丁生成,资源补丁合成及资源补丁加载. 本系列将从以下三个方 ...

  3. [spring源码] 小白级别的源码解析ioc(二)

    之前一篇,整体描述了一下 Spring的整体概况和 jar包的介绍. 现在开始进入具体的源码解析,从本篇开始,先介绍spring的ioc容器.之前也看过一些介绍spring源码的, 有的是只讲整体的接 ...

  4. JDK8源码解析 -- HashMap(二)

    在上一篇JDK8源码解析 -- HashMap(一)的博客中关于HashMap的重要知识点已经讲了差不多了,还有一些内容我会在今天这篇博客中说说,同时我也会把一些我不懂的问题抛出来,希望看到我这篇博客 ...

  5. MyBatis源码解析(十二)——binding绑定模块之MapperRegisty

    原创作品,可以转载,但是请标注出处地址:http://www.cnblogs.com/V1haoge/p/6758456.html 1.回顾 之前解析了解析模块parsing,其实所谓的解析模块就是为 ...

  6. mybatis源码-解析配置文件(二)之解析的流程

    目录 1. 简介 2. 配置文件解析流程分析 2.1 调用 2.2 解析的目的 2.3 XML 解析流程 2.3.1 build(parser) 2.3.2 new XMLConfigBuilder( ...

  7. django源码解析之BigIntegerField (一)

    要分析django的源码,来更深入的学习django,是一个不错的方法,可惜需要大量的时间. 所以,能分析多少就是多少吧. 本次源码分析以1.4.16为基础. 用sublime 打开下载的源码,使用 ...

  8. Mybaits 源码解析 (十二)----- Mybatis的事务如何被Spring管理?Mybatis和Spring事务中用的Connection是同一个吗?

    不知道一些同学有没有这种疑问,为什么Mybtis中要配置dataSource,Spring的事务中也要配置dataSource?那么Mybatis和Spring事务中用的Connection是同一个吗 ...

  9. bitcoin 源码解析 - 交易 Transaction(二) - 原理篇

    这篇文章我断断续续写了呃···· 应该快三个星期了? 所以前后的风格可能差别相当大.真是十分的怠惰啊··· 最近实在是不够努力.用python重写bitcoin的项目也卡在网络编程部分(这方面真是我的 ...

随机推荐

  1. Rplidar学习(三)—— ROS下进行rplidar调试

    一.建立工作空间.编译包 mkdir -p ~/catkin_rplidar/src #创建目录 cd ~/catkin_rplidar/src #打开目录 #下载rplidar_ros数据包,进行移 ...

  2. C#程序证书创建工具 (Makecert.exe)

    原文地址:https://msdn.microsoft.com/zh-cn/library/bfsktky3(VS.80).aspx 证书创建工具生成仅用于测试目的的 X.509 证书.它创建用于数字 ...

  3. ConcurrentHashMap vs Collections.synchronizedMap()不同

    之前项目中,有用到过Collections.synchronizedMap(),后面发现当并发数很多的时候,出现其他请求等待情况,因为synchronizedMap会锁住所有的资源,后面通过查阅资料, ...

  4. mvc 使用预置队列类型存储异常对象

    using PaiXie.Utils; using System; using System.Collections.Generic; using System.Linq; using System. ...

  5. asp.net与C# path.GetFullPath 获取上级目录

    string path = new directoryinfo("../").fullname;//当前应用程序路径的上级目录 获取当前目录可以使用appdomain.curren ...

  6. NTC与PTC压敏电阻在电源电路中起的作用

    https://wenku.baidu.com/view/e39beafdfab069dc502201f9.html 压敏电阻的作用 http://www.eepw.com.cn/article/27 ...

  7. python 多进程,实际上都没有运行,sleep

    进程以及状态 1. 进程程序:例如xxx.py这是程序,是一个静态的 进程:一个程序运行起来后,代码+用到的资源 称之为进程,它是操作系统分配资源的基本单元. 不仅可以通过线程完成多任务,进程也是可以 ...

  8. Mybatis mark 勿看

    Mybatis底层原理总结(一) 2018年01月11日 11:51:06 阅读数:2668 本文适合对Mybatis有一定了解的. 1. Mybatis 读取XML配置文件后会将内容放在一个Conf ...

  9. groupby elasticsearch

    GET usertag/usertag/_search { "query": { "match": { "tagname": "春 ...

  10. “TableDetails”中列“IsPrimaryKey”的值为DBNull. Mysql EntityFramework

                                                                                Entity Framework连接MySQL时 ...