In this section, we will explore how Django handles data through its powerful Object-Relational Mapping (ORM) system. We'll cover the basics of creating models, interacting with the database, and performing CRUD (Create, Read, Update, Delete) operations.

Key Concepts

  1. Django Models: Represent the structure of your database.
  2. ORM (Object-Relational Mapping): Allows you to interact with the database using Python code instead of SQL.
  3. Migrations: Manage changes to your database schema over time.

Creating a Model

A model in Django is a Python class that subclasses django.db.models.Model. Each attribute of the model represents a database field.

Example

# models.py
from django.db import models

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    birth_date = models.DateField()

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

Explanation

  • first_name, last_name, and birth_date are fields in the Author model.
  • models.CharField and models.DateField are field types provided by Django.
  • The __str__ method is used to return a human-readable representation of the model.

Making Migrations

After defining your models, you need to create and apply migrations to update the database schema.

Commands

  1. Create Migrations: Detect changes in models and create migration files.

    python manage.py makemigrations
    
  2. Apply Migrations: Apply the migration files to the database.

    python manage.py migrate
    

Interacting with the Database

Django provides a powerful API to interact with the database using the ORM.

Creating Records

# Create a new author
author = Author(first_name="John", last_name="Doe", birth_date="1980-01-01")
author.save()

Reading Records

# Get all authors
authors = Author.objects.all()

# Get a specific author
author = Author.objects.get(id=1)

Updating Records

# Update an author's last name
author = Author.objects.get(id=1)
author.last_name = "Smith"
author.save()

Deleting Records

# Delete an author
author = Author.objects.get(id=1)
author.delete()

Practical Exercise

Task

  1. Create a new model called Book with the following fields:

    • title (CharField, max_length=100)
    • author (ForeignKey to Author)
    • published_date (DateField)
    • isbn (CharField, max_length=13)
  2. Make and apply migrations.

  3. Create a few Book records and interact with them using the ORM.

Solution

# models.py
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    published_date = models.DateField()
    isbn = models.CharField(max_length=13)

    def __str__(self):
        return self.title
# Create and apply migrations
python manage.py makemigrations
python manage.py migrate
# Interact with the Book model
from myapp.models import Author, Book

# Create a new book
author = Author.objects.get(id=1)
book = Book(title="Django for Beginners", author=author, published_date="2023-01-01", isbn="1234567890123")
book.save()

# Get all books
books = Book.objects.all()

# Update a book's title
book = Book.objects.get(id=1)
book.title = "Advanced Django"
book.save()

# Delete a book
book = Book.objects.get(id=1)
book.delete()

Common Mistakes and Tips

  • Forgetting to Apply Migrations: Always run makemigrations and migrate after changing models.
  • Incorrect Field Types: Ensure you use the correct field types for your data.
  • Not Using ForeignKey Correctly: Remember to specify on_delete behavior for ForeignKey fields.

Conclusion

In this section, we covered the basics of Django models and databases. You learned how to create models, make and apply migrations, and perform CRUD operations using Django's ORM. This knowledge is fundamental for building any Django application that interacts with a database. In the next section, we will dive into the Django Admin Interface, which provides a powerful way to manage your data.

© Copyright 2024. All rights reserved