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

查看:586
本文介绍了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

推荐答案

从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

所以基本上这个实例变量是用来知道模型实例已经写入一个 db (知道Django支持多个db后端)并保存<$ c $使用c> db ,此实例变量属性添加保存模型实例,它主要用于(如上面的代码中的注释),用于验证主键是唯一的

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天全站免登陆