Connecting two models - 30 days of Django

Connecting two models - 30 days of Django

/ #Django


Today, we are going to make it possible to connect a task to a category.

Django ForeignKeys

There are a couple of ways to connect two database models. This is usaully done with a foreignkey field og a manytomany field. In this part, we we'll cover foreignkey. This perfect for when we want one category to have many tasks. It also makes it easy to find out which category a certain task belongs to.

Let's open up task/models.py and do some changes there:

from category.models import Category # New, 1

Class Task(models.Model):
    category = models.ForeignKey(Category, related_name='tasks', on_delete=models.CASCADE) # New, 2
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)
    is_done = models.BooleanField(default=False)

1. First we import the category model we have created.
2. Here, we add a new field called category, which is a foreignkey. We pass in the category model and set something called a related name. This makes it really easy to get all the tasks which belongs to a category. The "on_delete=models.CASCADE" means that if we delete a category, we also want to delete all of the connected tasks.

Next step then is to update the database again:

$ python3 manage.py makemigrations

This is the same command as when we created the database models, but it's also used for updating them as well.

$ python3 manage.py migrate

When this is done, the task table in the database should be updated. NB NB NB:
You might be asked to set a default category or similar here, just type 1 on your keyboard.

Summary

So, now we have tasks and categories + they are connected to eachother. So tomorrow, we will continue by showing categories on the website and the tasks connected to it.

Table of contents

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.