Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically import models on Django shell launch

Tags:

python

django

I'm tired of typing from account_import.models import ImportFile every time I open my Django shell. Is there a way to automatically run this command whenever I fire up my shell?

like image 211
Jason Swett Avatar asked Feb 01 '11 13:02

Jason Swett


People also ask

How import all models in Django?

To do this, create a directory called /«project»/«app_name»/models , inside it put __init__.py (to declare it as a module) and then create your files inside there. You then need to import your file contents into the module in __init__.py . You should read about Python modules to understand this.

How do I import models into view?

First, import the models you wish to use into your application's views.py file. Within the view you wish to use, query the model to get the data you want to present. Pass the results from your model into the template's context. Setup your template to present the data to the user in whatever way you wish.

What does import mean in Django?

A relative import is used to retrieve a resource relative to the current path you are on. So if you are currently working inside app1 -> views.py and you want to import hello_world.py to your views you can use . to specify a relative import to the current file you are working on.


2 Answers

install django-extensions, one of the commands it features (shell_plus) is providing the context for your models. https://github.com/django-extensions/django-extensions

So, instead of ./manage.py shell you can use ./manage.py shell_plus so that everything is imported.

like image 105
Uku Loskit Avatar answered Oct 10 '22 23:10

Uku Loskit


http://docs.python.org/using/cmdline.html#envvar-PYTHONSTARTUP

If you set the environment variable PYTHONSTARTUP to a file, this will be run first whenever you start a python shell.

like image 43
Daren Thomas Avatar answered Oct 11 '22 00:10

Daren Thomas