6

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?

Chirdeep Tomar
  • 4,281
  • 8
  • 37
  • 66

2 Answers2

1

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.

Andrew Hows
  • 1,429
  • 10
  • 16
  • 1
    Nope. As far as I can tell, running database stuff at load-time is not supported. I fixed my problem, ultimately, by re-writing it into a management command that was run when we deployed. The management command generated data and stored it in the database, and the app was then able to fetch it from the database. – Andrew Hows Apr 07 '15 at 06:09
1

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)

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
GrvTyagi
  • 4,231
  • 1
  • 33
  • 40