3

I am working on Django project. I need to create an object only once when the server initially starts. I want to use the methods associated with this particular object everytime a user accesses a particular page, that is I want the attributes and methods of this object to be accessible in views without having to instantiate the object again and again.

How exactly do i do it?

aakashgupta.0205
  • 647
  • 1
  • 8
  • 23
  • It's not ideal, but you could checkout this: https://docs.djangoproject.com/en/dev/ref/applications/#django.apps.AppConfig.ready – Shang Wang Apr 05 '16 at 18:44
  • Actually, instantiating that object hits to the database. And retrieves the same data always. So i want to avoid that and want to instantiate it once at the beginning, and still be able to use the retrieved data in my views – aakashgupta.0205 Apr 05 '16 at 18:46
  • Then you need to keep it in django sessions, it's per user basis: https://docs.djangoproject.com/en/1.9/topics/http/sessions/ – Shang Wang Apr 05 '16 at 18:48
  • instead, is it possible to have a global object which is instantiated when the server starts? – aakashgupta.0205 Apr 05 '16 at 19:02
  • http://stackoverflow.com/questions/2680902/python-django-global-variables – Shang Wang Apr 05 '16 at 19:05
  • Using global objects in a Django application is unusual, and most often wrong. It can be done, but it is always a hacky and non-standard thing. It seems like you want to do this as an optimization. Have you measured the performance impact of creating the object for every request, and have you concluded that it incurs a significant cost? Have you explored the possibility of optimizing the code that creates the object instead? In other words, are you certain that creating a global object is the right solution to your problem? – koniiiik Apr 05 '16 at 19:15
  • Yes. It does improve the performance because everytime i instantiate that object, it makes about a couple of hits to the database which leads to a comparatively slower rendering of the page. – aakashgupta.0205 Apr 05 '16 at 19:40
  • 1
    If it hits the database, that's only more reason *not* to have a single global instance for the entire lifetime of your server process. What if the database values change? Then you'd have to reload the server in order to make the change take effect. Two DB queries shouldn't make any significant difference, unless you're doing something very complex, and even then, you're most likely better off figuring out how to optimize those queries instead of hacking global objects into your application. Global objects have many pitfalls and corner cases, and you should only use them as the last resort. – koniiiik Apr 07 '16 at 20:49

1 Answers1

1

Try to make a fixture and before running server use manage.py loaddata

mmz2000
  • 48
  • 4