Lesson 18 - Database Migration
LEARN
Complete Your Projects
- Project 1 - Setup development tools
- Project 2 - Build a simple app
- Project 3 - Application Hosting
- Project 4 - TemplateView
- Project 5 - Data Models
- Project 6 - Data Model Views
- Project 7 - User Authentication
Superhero Data Model
Superhero (name, identity)
hero/models.py
class Superhero(models.Model):
name = models.CharField(max_length=100)
identity = models.CharField(max_length=100)
description = models.TextField()
strength = models.CharField(max_length=100)
weakness = models.CharField(max_length=100)
image = models.CharField(max_length=100)
Data Migrations
Create the scripts to update the database
Apply the migrations
python manage.py makemigrations hero
python manage.py migrate
Add Columns to Existing Tables
- Tables may already have data
- Must say how to fill the new columns
- Set default keyword argument in new fields added
Changes to the Database
- Databases can be modified
- Old data must be migrated to the new structure
Create a Superhero record
Create an object from the backdoor
python manage.py shell
from hero.models import Superhero
Superhero.objects.create(name="Hulk", identity="Bruce Banner")
Superhero.objects.create(name="Iron Man", identity="Tony Stark")
Superhero.objects.all()
Get An Object
By Name
Superhero.objects.get(name="Hulk")
By Identity
Superhero.objects.get(identity="Tony Stark")
By Primary Key
Superhero.objects.get(pk=2)
Show the Objects
hero/models.py
class Superhero(models.Model):
name = models.CharField(max_length=20)
identity = models.CharField(max_length=20)
def __str__(self):
return self.name
Add Data to Django Views
templates/page.html
<h1>{{ title }}</h1>
<p>
Hero Name: {{ hero.name }}
</p>
<p>
Secret Identify: {{ hero.identity }}
</p>
<p>
SHIELD Number: {{ hero.pk }}
</p>
Setting View Context
pages/views.py
class HomeView(TemplateView):
template_name = "page.html"
def get_context_data(self, **kwargs):
return {
'title': 'My Home Page',
'hero': Superhero.objects.get(identity="Tony Stark"),
}
BUILD
Demo of Data Migration
- Shows how to manage user authentication
- Book Builder Demo
- Software Planner
To Do List
- Test
- CRUD Test
- Views Test
- Fix
- Extend
- Add Fields to Book
- Extend views to show all fields
- Improve
- Setup command aliases
- Migrate database
- Simplify code
- Use CRUD Test Pattern
- Use Views Test Pattern