UNC BACS 350

Web Apps with Python/Django

Logo

Lesson 18 - Database Migration

LEARN

Complete Your Projects

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

Changes to the Database

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

To Do List