首页 > 代码库 > django源码解析之 BooleanField (二)

django源码解析之 BooleanField (二)

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, 1):            return True        if value in (f, False, 0):            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 (1, 0):            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 函数

 1     def to_python(self, value): 2         if value in (True, False): 3             # if value is 1 or 0 than it‘s equal to True or False, but we want 4             # to return a true bool for semantic reasons. 5             return bool(value) 6         if value in (t, True, 1): 7             return True 8         if value in (f, False, 0): 9             return False10         msg = self.error_messages[invalid] % str(value)11         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 (二)