[Answer]-Django Startup script for loading values into tables

1๐Ÿ‘

โœ…

I would load them into a CONTEXT_PROCESSOR so that they are available in all templates.

if you need it available as global variables, simple load them in a custom script.py file that you import into the views.py file you need it in.

edit:

you should also consider caching the results from the database and either saving in the SESSION or look into running memcached if the site could see a lot of traffic.

๐Ÿ‘คwarath-coder

0๐Ÿ‘

If you have some tables which are having same values everytime(staic values).
You can write your own [fixture][1] which define all values we are going to store into those tables.
You can create a directory of name fixtures into app folder.
Directory example :

|- my_app
|    |- fixtures
|           |- static_content.json

static_content.json can looks like

[
  {
    "model": "myapp.model1",
    "pk": 1,
    "fields": {
      "first_name": "test",
      "last_name": "Test_last"
    }
  },
  {
    "model": "myapp.model2",
    "pk": 1,
    "fields": {
      "age": "21",
      "email": "foo@foo.com"
    }
  }
]

before starting server by python manage.py runserver we can load our fixtures into our database by using below command.

python manage.py loaddata <fixturename>
Ex.   python manage.py loaddata my_app/static_content.json

above command will work as a startup script for loading values into db tables.

๐Ÿ‘คPrashant Gaur

Leave a comment