UNC BACS 350

Web Apps with Python/Django

Logo

Lesson 27 - Database Join

LEARN

Complete Your Projects

Today

Real world Engineering

Introducing a new mentoring program

Benefits

Requirements

Some students need help

Relational Data

Foreign Key

Relational Example

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) markdown = models.TextField() html = models.TextField() document = models.CharField(max_length=200)

# Bad
book = models.CharField(max_length=200)

```

Superhero News

python class Article(models.Model): hero = models.ForeignKey(Hero, on_delete=models.CASCADE) order = models.IntegerField() title = models.CharField(max_length=200) markdown = models.TextField() html = models.TextField()

Custom Queries in List View

Django for Beginners - Chapter 15

BUILD

Book Builder Demo

Limitation of Week 9

Work Needed

Chapters in Book

List the Chapters in the Book

book/views.py

```python

urls.py

path('book/', BookDetailView.as_view(), name='book_detail'),

class BookDetailView(DetailView): template_name = 'book_detail.html' model = Book

def get_context_data(self, **kwargs):
    book = Book.objects.get(pk=self.kwargs['pk'])
    return dict(object=book, chapters=Chapter.objects.filter(book=book.title))

```

Chapters in Book

Show the Chapters in the Book in detail view

templates/book_detail.html

```html

{% for chapter in chapters %} {% endfor %}
{{ chapter.book }} Chapter {{ chapter.order }} - {{ chapter.title }} Edit Delete

```

Project 10 - Superhero News

Project 10 - Views

Project 10 - Data

Project 10 - Tests