Basic Shell Usage - Interactive Python Console in Django
The Django shell is a tool that we have available to test the Django project, just as we have with the session, in other words, it allows us to interact with the application using commands, it is an extremely useful tool when we want to test connections to the database using models, we can query the data structure returned from a query or similar from the command line without needing us to implement test views/controllers to do these types of checks.
This tool is available from the Django CLI using the following command:
$ python manage.py shellWhich you must run with the Django server stopped; once the previous command is executed, you should see an output similar to the following:
Python 3.X (tags/v3.12.0:0fb18b0, Oct 2 2026, 13:03:39) [MSC v.1935 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
From here, we can interact with the application, for example make connections to the database through the models. To do this, the first thing we must do is load the resource that you want to test:
>>> from comments.models import CommentWith this, we have loaded the model called Comment and we can perform the operations on the model.
Get all records:
>>> comments = Comment.objects.all()
<QuerySet [<Comment: Comment #1>, <Comment: Comment #2>, <Comment: Comment #3>, <Comment: Comment #4>, <Comment: Comment #5>]>
Obtain a record by PK:
>>> comment = Comment.objects.get(pk=1In the example above, the comment with the ID of 1 must exist, if the comment does not exist, Django will throw an exception:
in get
raise self.model.DoesNotExist(
comments.models.Comment.DoesNotExist: Comment matching query does not exist.To delete a record:
>>> comment.delete()To save an instance of an object in the database, that is, to create or update a record in case it has the ID set:
comment.save()To obtain data in a filtered way:
>>> Comment.objects.all().filter(text="contenido")Where the parameter of the filter() function refers to an attribute of the model.
To get records based on a condition:
Comment.objects.get(text="contenido")To bring ordered records:
Comment.objects.order_by('date_posted')To delete a record:
comment.delete()Or using a shortcut get_list_or_404:
>>> from django.shortcuts get_list_or_404
>>> get_object_or_404(Comment, pk=pk)These are just some operations that we can perform with the Django ORM, but they are the ones that we are going to use in the next section to create our comments CRUD.
Next step, using Signals in Django to perform actions based on notifications.
I agree to receive announcements of interest about this Blog.
We will learn how to use the Django Shell: python manage.py shell To be able to execute commands as if they were defined in a view, it is ideal for testing all kinds of scripts and evaluating their operation.