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
- Django Models: Represent the structure of your database.
- ORM (Object-Relational Mapping): Allows you to interact with the database using Python code instead of SQL.
- 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
, andbirth_date
are fields in theAuthor
model.models.CharField
andmodels.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
-
Create Migrations: Detect changes in models and create migration files.
python manage.py makemigrations
-
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
Practical Exercise
Task
-
Create a new model called
Book
with the following fields:title
(CharField, max_length=100)author
(ForeignKey toAuthor
)published_date
(DateField)isbn
(CharField, max_length=13)
-
Make and apply migrations.
-
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
# 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
andmigrate
after changing models. - Incorrect Field Types: Ensure you use the correct field types for your data.
- Not Using
ForeignKey
Correctly: Remember to specifyon_delete
behavior forForeignKey
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.
Django Web Development Course
Module 1: Introduction to Django
- What is Django?
- Setting Up the Development Environment
- Creating Your First Django Project
- Understanding Django Project Structure
Module 2: Django Basics
- Django Apps and Project Structure
- URL Routing and Views
- Templates and Static Files
- Models and Databases
- Django Admin Interface
Module 3: Intermediate Django
Module 4: Advanced Django
- Advanced Querying with Django ORM
- Custom User Models
- Django Signals
- Testing in Django
- Performance Optimization