DEV Community

Loftie Ellis
Loftie Ellis

Posted on • Edited on

2 2

Django Console tip: autoload your models

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()
Enter fullscreen mode Exit fullscreen mode

Only to greeted with:

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

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

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
Enter fullscreen mode Exit fullscreen mode

Originally posted at https://loftie.com/post/django-console-tip

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay