Featured image of post Django ORM In a Nutshell

Django ORM In a Nutshell

Python ORM

Python Django ORM In a Nutshell


Setting Up Django ORM

Before we dive in, let’s set up Django in a project. If you haven’t installed Django yet, do this:

1
pip install django

Then, create a new Django project:

1
2
3
django-admin startproject myproject
cd myproject
python manage.py startapp myapp

Now, go to settings.py and configure your database. By default, Django uses SQLite, but you can change it to PostgreSQL, MySQL, or whatever suits your fancy.

Example for PostgreSQL:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'myuser',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

Defining Models (A.K.A Your Database Tables)

In Django, a model is a Python class that represents a database table. You define your models in models.py inside your app.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(unique=True)
    
    def __str__(self):
        return self.name

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    published_date = models.DateField()
    
    def __str__(self):
        return self.title

What’s happening here?

  • Author and Book are two tables.
  • CharField, EmailField, and DateField define the types of data these fields hold.
  • ForeignKey sets up a relationship between books and authors.
  • __str__() makes Django display readable names in the admin panel.

Run migrations to apply these models to your database:

1
2
python manage.py makemigrations
python manage.py migrate

Boom! Your database is now ready to store authors and books.


Querying Data (The Fun Part)

Alright, let’s talk about CRUD—Create, Read, Update, and Delete. This is where Django ORM really shines.

Creating Data

Adding new records is as easy as pie:

1
2
3
>>> from myapp.models import Author, Book
>>> author = Author.objects.create(name="J.K. Rowling", email="jk@example.com")
>>> book = Book.objects.create(title="Harry Potter", author=author, published_date="1997-06-26")

Reading Data

Fetching data? Piece of cake.

1
2
3
>>> books = Book.objects.all()  # Get all books
>>> first_book = Book.objects.first()  # Get first book
>>> books_by_rowling = Book.objects.filter(author__name="J.K. Rowling")  # Filter books

Updating Data

Want to update a book’s title? No problem.

1
2
3
>>> book = Book.objects.get(id=1)
>>> book.title = "Harry Potter and the Sorcerer’s Stone"
>>> book.save()

Deleting Data

Deleting is just as easy:

1
>>> book.delete()

Just like that, no more Harry Potter in the database. (Oops!)


Django ORM vs Raw SQL

If you’re wondering how Django ORM compares to raw SQL, check out this handy table:

FeatureDjango ORMRaw SQL
ReadabilitySuper clean and PythonicSQL can be verbose and complex
PerformanceOptimized but slightly abstractedFine-tuned control
SecurityBuilt-in protection against SQL injectionRequires manual handling
PortabilityWorks across multiple databasesTied to a specific SQL dialect
FlexibilityLimited to ORM’s capabilitiesTotal control

Django ORM is great for most cases, but if you need super complex queries, raw SQL might still be your best bet.


Running Raw SQL in Django ORM

Sometimes, ORM doesn’t cut it, and you need to write raw SQL. You can do that like this:

1
2
3
4
5
from django.db import connection

with connection.cursor() as cursor:
    cursor.execute("SELECT * FROM myapp_book")
    books = cursor.fetchall()

Use with caution—raw SQL is powerful but also dangerous if you’re not careful!


Key Ideas Table

ConceptSummary
Django ORMA way to interact with databases using Python classes instead of raw SQL
ModelsRepresent database tables using Python classes
QueriesCRUD operations (Create, Read, Update, Delete) using Pythonic syntax
MigrationsDjango’s way of applying database changes automatically
Raw SQLCan be used when ORM isn’t enough, but should be used carefully

References