What is ORM?
ORM (Object-Relational Mapping) is a technique that lets you interact with your database, like creating tables and performing CRUD operations, using an object-oriented paradigm.
In simpler terms, you can think of a database table as a class, and each record in that table as an instance (object) of that class. Creating a class in Django corresponds to creating a table in the database. Instantiating an object of that class adds a new record. Deleting an object removes a record. Changing an object's attribute modifies the corresponding field's value in the database. Iterating over objects or querying their attributes retrieves data from the database.
The following examples show typical commands used in Django views.
Create
There are two main approaches: using the create() method or the save() method.
from app01.models import *
# Method 1: Using create() with direct parameters
Author.objects.create(name='Alvin')
# Method 2: Using create() with a dictionary
Author.objects.create(**{"name": "alex"})
# Method 3: Using save() after constructing the object
author = Author(name="alvin")
author.save()
# Method 4: Using save() by setting attributes after instantiation
author = Author()
author.name = "alvin"
author.save()
Note: create() is the action of creating the record, and save() is the action of persisting it. Both are necesary; omitting one will not work.
Delete
You can delete objects using the delete() method on a queryset. For many-to-many relationships, use remove() or clear().
>>> Book.objects.filter(id=1).delete()
(3, {'app01.Book_authors': 2, 'app01.Book': 1})
# For many-to-many relationships:
# Forward (from the model that defines the relation)
book = models.Book.objects.filter(id=1)
# Clear all related authors for this book
book.author.clear()
# Remove a specific author by id
book.author.remove(2)
# Remove multiple authors by id list (unpack the list with *)
book.author.remove(*[1, 2, 3, 4])
# Reverse (from the related model)
author = models.Author.objects.filter(id=1)
# Clear all related books for this author
author.book_set.clear()
Update
There are two ways to update records: using the update() method on a queryset, or using save() on an instance.
# --------------- Method 1: update() sets specific fields directly ---------------
models.Book.objects.filter(id=3).update(title="PHP")
# Generated SQL:
# UPDATE "app01_book" SET "title" = 'PHP' WHERE "app01_book"."id" = 3; args=('PHP', 3)
# --------------- Method 2: save() resets all attributes (less efficient) ---------------
obj = models.Book.objects.filter(id=3)[0]
obj.title = "Python"
obj.save()
# Generated SQL:
# SELECT "app01_book"."id", "app01_book"."title", "app01_book"."price",
# "app01_book"."color", "app01_book"."page_num",
# "app01_book"."publisher_id" FROM "app01_book" WHERE "app01_book"."id" = 3 LIMIT 1;
#
# UPDATE "app01_book" SET "title" = 'Python', "price" = 3333, "color" = 'red', "page_num" = 556,
# "publisher_id" = 1 WHERE "app01_book"."id" = 3;
Query
Here are the common API methods for querying data:
# <1> filter(**kwargs): Returns objects that match the given filter conditions.
# <2> all(): Returns all objects.
# <3> get(**kwargs): Returns the single object matching the conditions. Raises an error if there are zero or more than one matches.
# The following methods are added after initial filtering (e.g., objects.filter().values()):
# <4> values(*field): Returns a QuerySet of dictionaries (not model instances).
# <5> exclude(**kwargs): Returns objects that do NOT match the given conditions.
# <6> order_by(*field): Sorts the results.
# <7> reverse(): Reverses the ordering of the results.
# <8> distinct(): Removes duplicate records from the result.
# <9> values_list(*field): Similar to values(), but returns tuples instead of dictionaries.
# <10> count(): Returns the number of objects matching the query.
# <11> first(): Returns the first record.
# <12> last(): Returns the last record.
# <13> exists(): Returns True if the QuerySet contains any records, otherwise False.
Summary
Django ORM provides a powerful and intuitive way to interact with your database using Python objects. Understanding these CRUD operations is fundamental to building Django applications efficient.