Mark when instance is loaded from database for pre-/post-init receivers.
|Reported by:||Vlastimil Zíma||Owned by:||nobody|
|Component:||Database layer (models, ORM)||Version:||1.4|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
There is no way to find out if instance exists in database until initializing is complete. There is attribute Model._state.adding, but it is set after instance is initialized.
from django.db import models from django.db.models import signals class Parent(models.Model): pass def callback(instance, **kwargs) print instance._state.adding signals.post_init.connect(callback, sender=Parent) p = Parent.objects.get(pk=1) >>> True p._state.adding >>> False
Such flag can come handy to avoid subsequent SELECT queries to find out whether instance already exists in database.