在Django我有一些模型,比如说:
class Learner(models.Model):
birth_date = models.DateField(null=True, blank=True)
def is_of_age(self):
logging.debug(type(self.birth_date))
.....
和视图,比如说:
def overview(request):
learner = Learner.objects.get(.....)
logging.debug(type(learner.birth_date))
.....
为什么birth_date
的类型不同?
在model的方法中是<class 'dict'>
,而在view中是<class 'datetime.date'>
。你知道吗
模型字段在赋值时不会自动转换为正确的python类型-保存时仅转换为正确的数据库类型。Django不保证
birth_date
的类型,除了一些使用描述符的特殊字段(比如ForeignKey
等)。你知道吗从数据库检索到的数据以一致的方式转换为Python类型。我真的不知道它是否总是相同的类型,但对于相同的数据,它将是一致的。这是你能得到的唯一保证。你知道吗
这在
BooleanField
中变得更加明显。考虑以下简单模型:以下说明了这种行为:
相关问题 更多 >
编程相关推荐