Test your Queries before they make it into Production using the Django Shell

You have a database, you have a Django project and a couple third party Django apps that you installed. You create your models, and now you want to try to test a few queries to see if your models are actually going to work.

Where do I start? How can I test to see if my models are going to work? I wish I could access my database to run some SQL queries with Django to see them in action!

Don’t ever write queries in your Django apps before you are sure they are going to do what you want them to do.

What I tend to do, is I open up my Python interpreter. Oh, not just any Python interpreter, but the one that comes with Django.

$ ./manage.py shell

At this point, you can run some Django queries to see what kind of data you will get. This will allow you see what happens when you perform some queries with a lot faster turn over rate. No need to worry about having to create a fake view, fake template, fake url, etc in order to see what query you need to use.

Let’s see an example.

Suppose we have a model called ‘Animal’ and 2 models ‘Cat’ and ‘Dog’ for some Polymorphism Django ORM magic (maybe you have a animal rescue website, so you need to query both Cats and Dogs in the same ‘Animal’ query):

class Animal(models.Model):
    name = models.CharField(max_length=40)
    created_data = models.DateTimeField(auto_now_add=True)

class Dog(Animal):
    house_broken = models.BooleanField(default=False)

class Cat(Animal):
    litter_trained = models.BooleanField(default=False)

Open up your shell using the command above.

Now, you need to import the models:

import pets.models import Animal, Dog, Cat

Now, simply run some queries to see what kind of data you retrieve.

dog1 = Dog.objects.create(name="Fred", house_broken=True)
dog2 = Dog.objects.create(name="Bob")
cat1 = Cat.objects.create(name="Freckles", litter_trained=True)
cat2 = Cat.objects.create(name="Socks")

dog1.save()
dog2.save()
cat1.save()
cat2.save()

animals1 = Animal.objects.all()
animals2 = Animal.objects.filter(created_data__year=2016)

You can do anything you want in the shell. It may take a little longer because you have to write everything out. The great part of this is, you don’t have to create anything other than the models. I created the models in seconds and I wanted to see what these queries would actually do.

Based on what I learned, I’m ready to start a website and start my pet rescue business! 🙂

Struggle with the Django Documentation?

If this post helped you, sign up for my newsletter and you'll get a new post each week that will help you master Django ABSOLUTELY FREE!

Powered by ConvertKit