Reputation: 4461
I have some static location data to load so that it is available throughout the application like an in-memory cache.
I tried to override ready() on AppConfig but data isn't loaded from the database, also ready() is getting called twice.
from django.apps import AppConfig
class WebConfig(AppConfig):
name = 'useraccount'
verbose_name = 'User Accounts'
locations = []
def ready(self):
print("Initialising...")
location = self.get_model('Location')
all_locations = location.objects.all()
print(all_locations.count())
self.locations = list(all_locations)
any hints?
Upvotes: 6
Views: 3506
Reputation: 4487
For load some static data in app create a separate file for get data
# file /app_util.py
def get_country():
if Student.objects.all().count == 0:
... # your code
else:
... # your code
import app_util and call it from url.py
# file /url.py
admin.autodiscover()
urlpatterns = patterns('equity_funds_investor_app',
# Examples:
url(r'^$', 'views.index'),
)
# make a call to save/get method
app_util.get_country()
Note: same process you can follow when you want to save/get some data at start of ur app url.py file process only one time when u make a first request after runserver and call your custom function(s)
Upvotes: 1
Reputation: 1438
Well, the docs ( https://docs.djangoproject.com/en/1.7/ref/applications/#django.apps.AppConfig.ready ) tell you to avoid using database calls in the ready() function, and also that it may be called twice.
Avoiding the double-call is easy:
def ready(self):
if self.has_attr('ready_run'): return
self.ready_run = True
...
But I'm still trying to find the right way to do database-based initialization, too. I'll update if I find anything.
Upvotes: 1