What is a Django Shell?

  • The Django shell is an interactive environment that allows us to explore the data stored in a project’s database

How to Examine Data Programmatically (i.e., Start a Shell Session)?

  • Use the command python manage.py shell to explore data in a project database.
  • Below is an example of an interactive shell session:
1python manage.py shell
2>>> from code_journals.models import Topic
3>>> Topic.objects.all()
4<QuerySet [<Topic: Data_Types>, <Topic: Lists>]>
  • In the second line, we import the model Topic from the code_journals.models module.
  • The method Topic.objects.all() is then used to get all the instances of the model Topic
  • The QuerySet list is returned

Looping through a QuerySet:

  • We can loop over a queryset, just as we’d loop over a list.
  • Example: View the ID that’s been assigned to each topic object:
1>>> topics = Topic.objects.all()
2>>> for topic in topics:
3...     print(topic.id, topic)
4...
51 Data_Types
62 Lists
  • In the above, we store the queryset in topics and then print each topic’s id attribute and the string representation of each topic. We see that Data_Types has an ID of 1 and Lists has an ID of 2.

  • If you know the ID of a particular object, you can get the object and examine the attribute the object has. Let’s look at the text and date_added values for Data_Types:

1>>> t = Topic.objects.get(id=1)
2>>> t.text
3'Data_Types'
4>>> t.date_added
5datetime.datetime(2026, 10, 21, 8, 13, 0, 448914, tzinfo=<UTC>)
  • We can also look at the entries related to a certain topic. Previously, we defined the topic attribute for the Entry model. This was a ForeignKey (a connection between each entry and a topic).
  • We can use the following to get every entry related to a certain topic:
1>>> t.entry_set.all()
2<QuerySet [<Entry: Data Types: I just discovered that Python’s built-in types—int, float, str, list, tuple, and dict—are all objects, giving me flexibility and power in coding.>, <Entry: I was blown away by how Python's data types, from integers to dictionaries, can seamlessly handle different kinds of information without me needing to specify types explicitly.>, <Entry: I was amazed to discover that Python's data types range from simple integers and floats to complex objects like dictionaries and sets, each with its own unique properties.>, <Entry: Today I realized how versatile Python's data types are, from simple integers and floats to complex lists and dictionaries that can be nested like a puzzle.>, <Entry: I just learned that in Python every value, from ints to lists, is an object, which means data types are inherently flexible and easier to manipulate.>]>
  • To get data through a foreign key relationship, you use the lowercase name of the related model followed by an underscore and the word set.

How can I Exit a Django Shell Session?

  • On Windows enter: CTRL-Z and press ENTER