ForeignKey in Django- Explained


In this article, we explain the concept of ForeignKey in Django and how it is used.

Let's say we have 2 database tables, a database table of users and a database table of cars.

We want these 2 tables linked together, because one of the users in the Users database table owns one of the cars and each of the cars in the Cars database table is owned by one of the users in the Users database table.

So there is clearly a direct link between a relationship between users and cars (a user owns a car and a car is owned by a user).

Therefore, we want to establish a link between these 2 database tables.

And a foreign key is how we're able to establish this link.

The best way to learn this ForeignKey concept in Django is to actually go over some code.

So let's do that.

In the code below, we create users and we create a database table named cars and link them together.

So, in our code, we're going to use Django's built-in User Model.

We get this functionality from the line, from django.conf import settings

We then have to import models from django.db in order to create a database table.

We then create the User variable and set it equal to settings.AUTH_USER_MODEL

What this does is it just creates a user from Django's built in User Model.

We then create a database table called Car.

We create a name field for the Car database table. This name field is of type CharField and it can be up to 100 characters in length.

The first line after the creation of the Car database is how we link the User Model (User database table) to the Car database table.

We put in the variable in lowercase and set it equal to models.ForeignKey(User). This makes the 2 database tables linked, so that we can establish relationships such as this user owns this car and that user owns that car. Or this user owns these cars and that user own those cars.

So this is how ForeignKey can be used in Django models in order to link different models (database tables) together.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...