UNC BACS 350

Web Apps with Python/Django

Logo

Lesson 28 -  Linking Data Types

LEARN

Today

Django for Beginners - Chapter 15

Relational Data

Foreign Key

Relational Example

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

Book Builder Demo

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

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

```

BUILD

Testing Failure

Demo Code

Project 10 - Superhero News

Project 10 - Views

Project 10 - Data

Project 10 - Tests