Lesson 28 - Linking Data Types
LEARN
Today
- Testing data changes
- Add new data types (Data, Views, Routes, Tests)
Django for Beginners - Chapter 15
- Comments on Articles
- Articles app
- URL, Templates, Views
- ForeignKey - Comment, Article
Relational Data
- Data table point to each other
- Objects live in the tables
- Reduce the duplicate information
- Databases are joined by a query
Foreign Key
- Points to a record in another table
- Saves to ID of the record
- Guarantees that data is consistent
- Data duplication is removed
Relational Example
- Chapters belong to a Book
- Chapter Data Record
- book (points to a book ID)
- order
- title
Author Data Model
Create a representation for Authors
```python class Author(models.Model): name = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE)
```
Book Data Model
Create a representation for Chapters in the Book
python
class Book(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
Chapter Data Model
Create a representation for Chapters in the Book
python
class Chapter(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE)
order = models.IntegerField()
title = models.CharField(max_length=200)
Custom Queries in List View
- Find only matching objects
- Pass reference object by ID on URL
- Use get_queryset to filter objects
Book Builder Demo
- Implement data design (Author, Book, Chapter)
- Author <-- Book <-- Chapter
- Views support proper queries
- Book builder style
- Tests for Data/Views (Author, Book, Chapter)
Author's Books
List the Book by an Author
book/views.py
```python
urls.py
path('author/', AuthorDetailView.as_view(), name='author_detail'),
class AuthorDetailView(DetailView): template_name = 'author_detail.html' model = Author
def get_context_data(self, **kwargs):
author = Author.objects.get(pk=self.kwargs['pk'])
return dict(object=author, books=Book.objects.filter(author=author))
```
Chapters in Book
Show the Chapters in the Book in detail view
templates/book_detail.html
```html
{{ chapter.book }} | Chapter {{ chapter.order }} - {{ chapter.title }} | Edit | Delete |
```
BUILD
Testing Failure
- Personal story of process failure
- Changes to object model without testing
- Spent four hours trying to find the error
Demo Code
- Demo Code
- Follow along with my source code
- Clone my repo and edit the code
Project 10 - Superhero News
- Views
- Query for Articles about each Hero in HeroDetailView
- Add the article list to hero detail template
- Data
- Add hero as ForeignKey in Article
- Migrate
- Tests
- Hero Data
- Hero Views
- Article Data
- Article Views
Project 10 - Views
- Superhero Selector Page
- Profile Tab
- News Tab
- Article Views
- Hero Views
Project 10 - Data
- Investigator Data Type
- Investigator <-- Hero <-- Article
- Views support proper queries
- Hero News style
Project 10 - Tests
- Data/Views
- Investigator, Hero, Article