Django:ModelState的作用是什么?
抱歉,这不是编程问题,但是当我尝试内省我的类对象时,这引起了我的注意。
我找到了这个
{'user_id': 1, '_state': <django.db.models.base.ModelState object at 0x10ac2a750>, 'id': 2, 'playlist_id': 8}
作用是什么,作用是_state
什么ModelState
?
-
在Django源代码中,_state是在每个Model实例中定义的实例变量,该实例变量的实例
ModelState
定义为:class ModelState(object): """ A class for storing instance state """ def __init__(self, db=None): self.db = db # If true, uniqueness validation checks will consider this a new, as-yet-unsaved object. # Necessary for correct validation of new instances of objects with explicit (non-auto) PKs. # This impacts validation only; it has no effect on the actual save. self.adding = True
因此,基本上,该实例变量用于了解
Model
实例是否已写入db
(知道Django支持多个数据库后端)并保存db
使用的实例变量,该实例变量属性adding
在保存模型实例后设置为false
,并且大多数情况下使用(作为上面代码中的注释),用于验证主键是否唯一。