28

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?

daydreamer
  • 87,243
  • 191
  • 450
  • 722
  • 3
    Be careful if you use `_state` in any of your code. It's not documented, so its behaviour could change between versions of Django. – Alasdair Jul 19 '12 at 13:37
  • 5
    Interestingly, while the documentation doesn't seem to describe `_state`, it [instructs you to manipulate it](https://docs.djangoproject.com/en/1.9/ref/models/instances/#customizing-model-loading) when overriding `Model` classmethod `from_db`. – das-g Apr 14 '16 at 14:13

1 Answers1

41

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.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
mouad
  • 67,571
  • 18
  • 114
  • 106
  • 3
    another case where I wouldn't have to scroll horizontally if the code was kept to 79 cols or less. – Skylar Saveland Sep 19 '13 at 22:48
  • @SkylarSaveland I prefer soft 80-ish for my code, but yeah, the line length is among the most abused things in many otherwise popular libraries. Maybe their developers all have multiple huge monitors or perhaps they never do anything side-by-side, not even diff or merge... – Ivan Anishchuk Jan 18 '19 at 13:13