Login

Alternate method of autoloading Django models in ipython

Author:
drewr
Posted:
January 16, 2008
Language:
Python
Version:
.96
Score:
9 (after 9 ratings)

This is a little improvement to the idea from sheats a few days ago.

I like it over the previous solutions because it doesn't involve doing anything other than running ./manage.py shell inside your project directory. You don't have to create any files anywhere or remember to call anything, and ipython still works fine outside of a Django project.

Throw this code in ~/.ipython/ipy_user_conf.py (ipythonrc has apparently been deprecated).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def load_django_models():
    try:
        from django.db.models.loading import get_models
        for m in get_models():
            ip.ex("from %s import %s" % (m.__module__, m.__name__))
    except ImportError:
        print "INFO: could not find a django env"

...

def main():
    ...
    load_django_models()

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

jpt (on January 16, 2008):

great snippet, I use ipython for other things (virtually everything actually) so I changed the code to

def load_django_models():
    try:
        from django.db.models.loading import get_models
        for m in get_models():
            ip.ex("from %s import %s" % (m.__module__, m.__name__))
        print 'INFO: Loaded Django models.'
    except ImportError:
        pass

but other than that, terrific

#

chrisyoung (on June 15, 2009):

If you're using a virtualenv and ipython is having trouble finding your project settings, I found that adding this to the snippet helped:

os.environ["DJANGO_SETTINGS_MODULE"] = "settings"

#

Please login first before commenting.