Lesson 14 - Manipulating Data
LEARN
Week 5 - Data
- Lesson 12 - Data CRUD Operations
 - Lesson 13 - View Inheritance
 - Lesson 14 - Manipulating Data
 - Project 5 - Admin Views and View Inheritance
 - Django for Beginners - Chapter 5 - Blog App
 
Project 4
- Project 4 requirements do not require a database
 - Key Requirements
- List of hero with links
 - Details pages for all heros
 - Include a photo that is stored on your server
 
 
Project 5
- Key Requirements
- Admin views to create database for heroes
 - List of hero with links from database
 - Details pages for all heros from database
 - Include a photo that is stored on your server
 - View Inheritance (hero_theme.html)
 
 
Data Models
- ORM lets us write Data Models as Python Classes
 - Database is automatically updated
 - Migration updates the tables
 
Data Migrations
Create the scripts to update the database
Apply the migrations
python manage.py makemigrations hero
python manage.py migrate
CRUD
- CREATE - make a new record
 - READ - get one or more records
 - UPDATE - modify an existing record
 - DELETE - remove a record
 
Django Shell
A console window will let you execute Python code directly
Do all the CRUD operations
python manage.py shell
Data Model
- Superhero (name, identity)
 
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
- Tests the functions
 - Provides place to put business logic
 - Enable tests in small steps
 
You practice
- Create access functions in hero/hero.py
 - Build tests in hero/tests.py
 - Debug tests and functions one at a time
 - Create five tests (model, create, read, update, delete)