Working with database
Working with databases in Django involves defining models, performing CRUD (Create, Read, Update, Delete) operations, and managing migrations. Here’s a step-by-step guide on how to work with databases in Django:
Defining Models
- Create Models: Define your data models in Django by creating Python classes that inherit from
django.db.models.Model
.# models.py from django.db import models class Author(models.Model): name = models.CharField(max_length=100) biography = models.TextField() 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
- Field Types: Use Django's model fields (
CharField
,IntegerField
,ForeignKey
, etc.) to define the structure of your data. - Relationships: Establish relationships between models using
ForeignKey
,OneToOneField
, orManyToManyField
.
- Field Types: Use Django's model fields (
Creating and Applying Migrations
- Generate Migrations: After defining models, create migration files that define database schema changes.
python manage.py makemigrations
This command analyzes changes to your models and creates migration files in themigrations
directory of each app. - Apply Migrations: Apply migrations to synchronize the database schema with the current state of your models.
python manage.py migrate
Django executes these migrations to create or update database tables accordingly.
Performing CRUD Operations
- Creating Objects:
# views.py or interactive shell from myapp.models import Author, Book # Create a new author author = Author.objects.create(name='John Doe', biography='Lorem ipsum...') # Create a new book associated with the author book = Book.objects.create(title='Sample Book', author=author, published_date='2023-01-01')
- Reading Objects:
# views.py or interactive shell from myapp.models import Author, Book # Retrieve all authors authors = Author.objects.all() # Retrieve a specific book by title book = Book.objects.get(title='Sample Book')
- Updating Objects:
# views.py or interactive shell from myapp.models import Book # Update a book's title book = Book.objects.get(id=1) book.title = 'New Title' book.save()
- Deleting Objects:
# views.py or interactive shell from myapp.models import Author # Delete an author author = Author.objects.get(id=1) author.delete()
QuerySets and Methods
- Filtering:
# views.py or interactive shell from myapp.models import Book # Filter books published after 2020 books = Book.objects.filter(published_date__gte='2020-01-01')
- Ordering:
# views.py or interactive shell from myapp.models import Book # Order books by published date descending books = Book.objects.order_by('-published_date')
- Aggregation and Annotations:
# views.py or interactive shell from django.db.models import Count from myapp.models import Author, Book # Count the number of books per author authors_with_counts = Author.objects.annotate(num_books=Count('book'))
Using Django ORM in Views
- Views and Templates: Query data in views and pass it to templates for rendering.
# views.py from django.shortcuts import render from myapp.models import Book def book_list(request): books = Book.objects.all() return render(request, 'myapp/book_list.html', {'books': books})
- Handling Forms: Validate form data, save objects to the database, and redirect as needed.
# views.py from django.shortcuts import render, redirect from myapp.forms import BookForm def create_book(request): if request.method == 'POST': form = BookForm(request.POST) if form.is_valid(): form.save() return redirect('book_list') else: form = BookForm() return render(request, 'myapp/create_book.html', {'form': form})
Conclusion
Django’s ORM simplifies database interactions by providing a high-level API for defining models, performing queries, and managing migrations. By following these steps and exploring Django’s documentation, you can effectively work with databases and build robust web applications.