Best place to initialize a variable from a postgres database table after django project startup
I have a django project where I have some database tables.
One of the database tables is designed to store messages and their titles. This helps me to create/alter these messages from my django-admin.
Now I want to initialize a variable (as a dictionary) from this table as follows :
MY_MSGS = {record.name : {'title':record.title, 'message':record.message} for record in MyTable.objects.all()}
This must happen at the server startup for now.
MY_MSGS
must be accessible to the different view-files.
FYI I have multiple view-files that are all imported from views.py
I think the main concern is that you should not run the query immediately, but after Django has initialized the models, etc.
We can do that by postponing the load procedure, and do it when we really need a message, with:
def get_message(name):
cache = get_message.cache
if cache is None:
cache = get_message.cache = {
record.name: {'title': record.title, 'message': record.message}
for record in MyTable.objects.all()
}
return cache.get(name)
get_message.cache = None
and thus use this as a function, like:
get_message(my_record_name)
then it is of course still important to make sure you never call the function during initialization, so not pass this as a default=…
[Django-doc], etc. of a method field for example.
An extra advantage is that as long as you don't need any message, you don't fetch these. If we do, we will not do it a second time.
But usually that might be a problem: typically you don't restart the Django server very often in production, so the messages can remain the old ones for months.