Peter Sheats’ Blog

January 9, 2008

Autoloading Your Django Models

Filed under: Django — Peter Sheats @ 11:05 am

One of the great things about Python is the interactive shell. This allows you to try things out interactively before actually writing any permanent code.

I have been noticing how annoying it was to actually play with my Django code in the interactive shell because everytime you wanted to use a model you had to import it first. And what is worse, if you make some changes to the model you’re using, they won’t show up until you quit the shell, start it, and reimport the model again.

So I started snooping around the code behind the “./manage.py shell” command to see if there was a way to autoload all my Django models everytime I started the shell. I noticed that Django uses IPython by default if it is installed. So I installed IPython which offers a lot of helpful shortcuts and features for working with Python in an interpreter. I would definitely recommend checking it out if you use the Python interpreter a lot.

You can have IPython run a script everytime it starts up, so here’s how to get it to autoload all your Django models everytime you use “./manage.py shell”.

Create a python script with the following code. I just called it ipythonrc.py and put it in the root of my Django project.

from django.db.models.loading import get_models
for m in get_models():
    exec "from %s import %s" % (m.__module__, m.__name__)

 

Then edit ~/.ipython/ipythonrc and look for the section called “Section: Python files to load and execute” around line 566. Simply put the name of the file you created above in there like this:

execfile ipythonrc.py

That’s all there is to it. You should be able to run “./manage.py shell” and have immediate access to all your models.

Powered by WordPress