The Django Shell

The Django shell is simply a python shell that allows you to explore your models and apps. Let’s review the Avocado Cream burger we created for our burger joint. See my previous post about Django to get started. Open your project and enter the following commands.

python manage.py shell
from burgers.models import Burger

The first command tells Django to open the python shell. The second command imports the burger models we created previously. We can view the burgers I’ve setup using using Burger.objects.all() method.

>>> burgers = Burger.objects.all()
>>> for burger in burgers:
...     print(burger.id, burger)
1 Avocado Cream
2 BLTE
3 BBQ Bacon

We see above that we can use the shell just like any python shell. I’ve done a small for loop to print the database ID and name of each burger I created.

We can see the individual toppings for each burger as well. Below we use Burger.objects.get(id=3) to assign a burger to my_burger. We can then view the toppings using my_burger.topping_set.all()

>>> my_burger = Burger.objects.get(id=3)
>>> my_burger.topping_set.all()
<QuerySet [<Topping: BBQ Sauce, Bacon, Cheddar>]>

These commands allow us to access the database objects created by Django without having to write database queries. You can continue to explore your model in this way. Next, we’ll start to use this syntax to write pages for our Burger Joint site.

Read my next post in this series to learn about making pages for your Django site.

John

Leave a Reply

Your email address will not be published. Required fields are marked *