Sam1233
Sam1233

Reputation: 19

Django Startup script for loading values into tables

There are 6 tables in DB out of it 3 will have same values everytime like static values these values need to be loaded into tables when we do python manage.py runserver. what will be the approach for this do i need to have a script for it Any help would be appreciated.

Thanks.

Upvotes: 0

Views: 321

Answers (2)

warath-coder
warath-coder

Reputation: 2122

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.

Upvotes: 1

Prashant Gaur
Prashant Gaur

Reputation: 9828

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": "[email protected]"
    }
  }
]

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.

Upvotes: 0

Related Questions