Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

python - Django : What is the role of ModelState?

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

I found this

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

What is the role of _state and what ModelState does?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...