How to Link Database Tables Together in Django



Python


In this article, we show how to link database tables together in Django.

Let's say we have 2 closely related groups of data and they are linked together.

Let's say you have a table of books. For each book in this table, you have a another table named that stores the table of contents of each of the books.

These are very closely related data that you want linked.

For example, if you delete a book from the books table, then you want the corresponding table of contents in the table of contents table to be removed.

You wouldn't want the table of contents for a book to exist that's been deleted. You would want them both to either co-exist together or be deleted together, the majority of the times.

So we'll create code that creates a books table, comprising a list of books.

We then create a table of contents table, listing all of the chapters of the book.

This is the code shown below.



So, you can see that we have created two tables, a table named Books and a table named TableOfContents.

Every line creates a column for each of the tables, except for the first line after the creation of TableOfContents.

The line, books= models.ForeignKey(Books, on_delete=models.CASCADE), links the TableOfContents table to the Books Table. The statement, on_delete=models.CASCADE, makes it so that if we delete a book, the corresponding table of contents will also be deleted. This is because you don't want a table of contents to exist without the actual book in the table. You don't want standalone table of contents without the actual book. Therefore, it gives proper data management to our database tables. The two are linked, so that we have proper data utilization in our code.

And this is how database tables can be linked together in Django.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...