ToDo App in Django Part 4: Django ORM, Python Shell, and CRUD Operation

Hello internet people, welcome to the Learn Django by Doing Project Series. And we are making a todo app in Django. Hope you are enjoying it.

In the previous tutorial, we saw about Django URLs, views, and templates. Today we do the main operation for the todo app. Creating/adding a task, retrieve the task, update the task, and delete the task; In short CRUD operation in Django.

First, let’s understand Django ORM (object-relational mapper). So, activate your virtual environment.

Django ORM and Working with QuerySets

Django comes with a powerful database abstraction API that lets you create, retrieve, update, and delete objects easily.

The Django ORM is based on QuerySets. A QuerySet is a collection of database queries to retrieve objects from your database. You can apply filters to QuerySets to narrow down the query results based on given parameters.

Creating Objects

Open the terminal and run the following command to open the Python shell:

python3 manage.py shell

Then, type the following lines:

>>> from todolist.models import Task
>>> task=Task(title="Another task")
>>> task.save()
>>> 

Let’s understand above codes.

You create a Task instance with a custom title and storing it in task variable.

task=Task(title="Another task")

This object is in memory and is not persisted to the database.

Finally, save the Task object to the database using the save() method.

task.save()

The preceding action performs an INSERT SQL statement behind the scenes. You have seen how to create an object in memory first and then persist it to the database, but you can also create the object and persist it into the database in a single operation using the create() method, as follows:

>>> Task.objects.create(title="One more task")

Open admin site and open the tasks, you can see task is added.

Retrieving objects

Using the all() method:

Each Django model has at least one manager, and the default manager is called objects. You get a QuerySet object using your model manager. To retrieve all objects from a table, you just use the all() method on the default objects manager, like this:

>>> all_task=Task.objects.all()

This is how you create a QuerySet that returns all objects in the database. Note that this QuerySet has not been executed yet.

Django QuerySets are lazy, which means they are only evaluated when they are forced to be. This behavior makes QuerySets very efficient.

If you don’t set the QuerySet to a variable, but instead write it directly on the Python shell, the SQL statement of the QuerySet is executed because you force it to output results:

>>> all_task

Using get() method:

>>> Task.objects.get(title='Another task')

Not the best example but the get() method allows you to retrieve only a single object from the database.

Note that this method expects a result that matches the query. If no results are returned by the database, this method will raise a DoesNotExist exception, and if the database returns more than one result, it will raise a MultipleObjectsReturned exception. Both exceptions are attributes of the model class that the query is being performed on.

Using filter() method:

To filter a QuerySet, you can use the filter() method of the manager. For example, you can retrieve all tasks with a “task” word included.

>>> Task.objects.filter(title__icontains='task')

This equates to building the same QuerySet chaining multiple filters:

>>> Task.objects.filter(title__icontains='Task').filter(completed=False)

Using order_by() method:

You can order results by different fields using the order_by() method of the manager. For example, you can retrieve all objects ordered by their title, as follows:

>>> Task.objects.order_by('title')

Ascending order is implied. You can indicate descending order with a negative sign prefix, like this:

>>> Task.objects.order_by('-title')

Updating objects

Now get the object and we change the title of the task to something different and save the object again:

>>> task=Task.objects.get(title='Another task')
>>> task.title
'Another task'
>>> task.title="Another task is this..."
>>> task.title
'Another task is this...'
>>> task.save()

This time, the save() method performs an UPDATE SQL statement.

The changes you make to the object are not persisted to the database until you call the save() method.

Deleting objects

If you want to delete an object, you can do it from the object instance using the delete() method:

>>> task=Task.objects.get(id=2)
>>> task
<Task: blah blah blah...>
>>> task.delete()
(1, {'todolist.Task': 1})
>>> 

Note that deleting objects will also delete any dependent relationships for ForeignKey objects defined with on_delete set to CASCADE.

Here we perform CRUD operation in python shell. Same logic we will write and apply in the Django view.

Okay that’s it for the now. In the next tutorial we will apply this logic in our views. Hope you’re enjoying this series. Please share it with your friends.

Previous: ToDo App in Django Part 3: URLs, View, and Template in Django

Next: ToDo App in Django Part 5: Create, Retrieve, Update and Delete Task – CRUD Operation in Django

Leave a Comment

Copy link
Powered by Social Snap