Lesson 4
Creating Relationships Between Models
Connecting Models Together

Welcome back! After learning how to integrate SQLite3 with the Django ORM and create a simple model, it's time to extend those capabilities. In this unit, we'll focus on creating relationships between models. Just like in the real world, data often has connections and relationships that need to be represented within your database. By the end of this unit, you'll be comfortable defining these relationships in Django.

What You'll Learn

In this lesson, you’ll master the following:

  • Creating models that have relationships with each other
  • Connecting models using Django ORM
  • Creating views to handle data interactions involving related models

Firstly, let's consider a Category model that can be linked to multiple Todo items. This will allow each task to belong to a specific category. In your models.py, you define your models as follows:

Python
1from django.db import models 2 3class Category(models.Model): 4 name = models.CharField(max_length=100) 5 6 def __str__(self): 7 return self.name 8 9class Todo(models.Model): 10 task = models.CharField(max_length=200) 11 category = models.ForeignKey(Category, on_delete=models.CASCADE) 12 13 def __str__(self): 14 return self.task

Here, the Category model holds category names, and the Todo model has a foreign key connecting each task to a category. Foreign keys are used to establish relationships between models. In this case, the category field in the Todo model is a foreign key that links each task to a category.

Also, pay attention to the on_delete=models.CASCADE argument in the ForeignKey field. This argument specifies what happens when the linked category is deleted. In this case, it's set to CASCADE, which means that if a category is deleted, all tasks linked to that category will also be deleted.

Next, we’ll create views to handle adding new categories and tasks with their corresponding categories. Update your views.py file:

Python
1import json 2from django.http import JsonResponse 3from django.views.decorators.csrf import csrf_exempt 4from .models import Category, Todo 5 6def add_category(request): 7 if request.method == 'POST': 8 data = json.loads(request.body) 9 new_category = Category(name=data['name']) 10 new_category.save() 11 return JsonResponse({'id': new_category.id, 'name': new_category.name}, status=201) 12 return JsonResponse({'message': 'Invalid request'}, status=400) 13 14def add_todo_with_category(request): 15 if request.method == 'POST': 16 data = json.loads(request.body) 17 category = Category.objects.get(name=data['category']) 18 new_todo = Todo(task=data['task'], category=category) 19 new_todo.save() 20 return JsonResponse({'id': new_todo.id, 'task': new_todo.task, 'category': new_todo.category.name}, status=201) 21 return JsonResponse({'message': 'Invalid request'}, status=400)

These views will enable you to add new categories and assign tasks to them through API requests.

Finally, don’t forget to map these views in your urls.py file:

Python
1from django.urls import path 2from myapp import views 3 4urlpatterns = [ 5 path('add-category/', views.add_category, name='add_category'), 6 path('add-todo-with-category/', views.add_todo_with_category, name='add_todo_with_category'), 7]

This configuration sets up the URL routes to handle the creation of categories and tasks linked to them.

Now that we have both models and views in place, it’s time to test them out:

  1. First we need to create a category sending a a POST request to /add-category/ endpoint with the following JSON payload:

    JSON
    1{ 2 "name": "Work" 3}
  2. Next, we can create a task linked to the category sending a POST request to /add-todo-with-category/ endpoint with the following JSON payload:

    JSON
    1{ 2 "task": "Prepare presentation", 3 "category": "Work" 4}

After sending these requests, you should see the new category and task added to the database.

Why It Matters

Understanding how to create and manage relationships between models is crucial for building robust and well-structured applications. With these skills, you will be able to:

  • Represent complex data relationships in your applications
  • Simplify data retrieval and manipulation using Django’s ORM
  • Build powerful and scalable web applications

By the end of this lesson, you will have a solid grasp of how to define and manage relationships between different parts of your data. This knowledge will form the backbone of efficient database management in your Django projects.

Are you excited to put this new knowledge into practice? Let's dive into the practice section and start coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.