Found this lovely doc:
https://docs.djangoproject.com/en/2.0/ref/models/instances/#customizing-model-loading
But it leaves me with a thirst for more knowledge. My conclusion form
reading it is, that if I wanted to put a hook into some custom code that
always ran after data was loaded from the database, and after the model
instance is created (populated with data) I would need to dos something
like:
class Book(models.Model):
title = models.CharField(max_length=100)
@classmethod
def create(cls, title):
book = super().create(cls, title)
# hook to custom code here
return book
@classmethod
def from_db(cls, db, field_names, values):
book = super().from_db(cls, db, field_names, values)
# hook to custom code here
return book
def refresh_from_db(self, using=None, fields=None, **kwargs):
super().refresh_from_db(using, fields, **kwargs)
# hook to custom code here
Taking note that the last of these is an instance method and the first two are
class methods and returns nothing.
The documentation is not very clear in this space.
If that hook took the simple form of:
if hasattr(book_or_self, "_post_load") and callable(book_or_self._post_load):
book_or_self._post_load(book_or_self)
Then defining a model method _post_load(self) would provide a place to put code
that ran reliably before any other code could inspect the instance?
It seems a little clunky almost as if it would be neater if there were a signal
issued at that point in time by django base, but could be tidied up by writing
a new model class that derives from models.Model, like ModelWithPostLoadHooks
and deriving a model from that if it wanted to have such hooks.
Musing here, and wondering if I have it right.
Bernd.
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-users/9c2b8368-6620-4387-83a7-f52390a0e921%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.