Django console tip: autoload your models

Several times per day I would open the Django console to check some values from my models. I would type something like:

Post.objects.filter(user=User.objects.last(), state='published').count()

Only to greeted with:

Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'Post' is not defined

Of course I forgot to import the required models:

from users.models import User
from blog.models import Post
Post.objects.filter(user=User.objects.last(), state='published').count()
4

Wouldn’t it be nice to have it all automatically loaded when you open the console, the way it works in rails?
Luckily it is easy to do, all that is required is to add a few lines that execute when the console starts up:

from django.apps import apps

for _class in apps.get_models():
globals()[_class.__name__] = _class

If you use PyCharm then you can set it up from settings->Build, Execution, Deployment ->Console->Django Console

Image for post
Image for post
Django Console settings in PyCharm

And voila, from now on all your models are ready to use when you start.

Post.objects.filter(user=User.objects.last(), state='published').count()
4

Written by

Software developer and Rock Climber. https://loftie.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store