Django:ModelState 的作用是什么? [英] Django : What is the role of ModelState?

查看:35
本文介绍了Django:ModelState 的作用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,这不是编程问题,但当我试图内省我的类对象时,这引起了我的注意.

Sorry for not being this as programming question, but this caught my eye when I was trying to introspect my class objects.

我找到了这个

{'user_id': 1, '_state': <django.db.models.base.ModelState object at 0x10ac2a750>, 'id': 2, 'playlist_id': 8}

_state 的作用是什么,ModelState 有什么作用?

What is the role of _state and what ModelState does?

推荐答案

来自 Django 源代码,_state 是在每个 Model 实例中定义的实例变量,它是 ModelState 定义为:

From the Django source code, _state is an instance variable defined in each Model instance that is an instance of ModelState that is defined as:

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 后端)并保存 db 使用,这个实例变量属性adding保存模型实例,它主要用于验证主键是唯一的.

So basically this instance variable is used to know if the Model instance was already written to a db (knowing that Django support multiple db backends) and to hold the db used, this instance variable attribute adding is set to false after saving the model instance, and it's used mostly (as the comment in the code above) for validating if the primary keys is unique.

这篇关于Django:ModelState 的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆