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
- 1. Introduction
- 2. Installation and setup
- 3. How things work
- 4. The first Django app
- 5. Your first view
- 6. Your first template
- 7. Testing our site
- 8. Extending templates
- 9. Your first model
- 10. The admin interface
- 11. Showing contents from the model
- 12. Another app (category)
- 13. Connecting two models
- 14. Show list of categories
- 15. Category detail page