UNC BACS 350

Web Apps with Python/Django

Logo

Lesson 14 - Manipulating Data

LEARN

Week 5 - Data

Project 4

Project 5

Data Models

Data Migrations

Create the scripts to update the database

Apply the migrations

python manage.py makemigrations hero

python manage.py migrate

CRUD

Django Shell

A console window will let you execute Python code directly

Do all the CRUD operations

python manage.py shell

Data Model

hero/models.py

class Superhero(models.Model):
    name = models.CharField(max_length=20)
    identity = models.CharField(max_length=20)

CREATE

hero/hero.py

from .models import Superhero

def add_hero(hero_name, hero_id):
    return Superhero.objects.create(name=hero_name, identity=hero_id)

READ - List

hero/hero.py

def list_heroes():
    return Superhero.objects.all()

READ - Get

hero/hero.py

def get_hero(pk):
    return Superhero.objects.get(pk=pk)

def get_identity(id):
    return Superhero.objects.get(identity=id)

def get_hero_name(supername):
    return Superhero.objects.get(name=supername)

UPDATE

hero/hero.py

def set_hero_id(pk, id):
    w = get_hero(pk)
    w.identity=id
    w.save()

def set_hero_name(pk, name):
    w = get_hero(pk)
    w.name=name
    w.save()

DELETE

hero/hero.py

def delete_hero(pk):
    Superhero.objects.get(pk=pk).delete()

BUILD

Test CRUD

Use Django Tests to test the CRUD operations

hero/tests.py

from django.test import TestCase

from .models import Superhero
from .hero import list_heroes

class CrudTests(TestCase):

    def test_num_heroes(self):
        num_heroes = len(list_heroes())
        self.assertEqual(num_heroes, 0)

Test Each Operation

Test every function you write

def test_hero_model(self):
    pass

def test_create(self):
    pass

def test_read(self):
    pass

def test_update(self):
    pass

def test_delete(self):
    pass

Use the Query Functions

You practice