What is Foreign Key?
A Foreign Key is a field in one table that refers to the primary key of another table. Basically we uses Database system to handle complex data i.e number of tables. The concept Foreign Key plays an very important role in RDBMS(Relational Database Management System), where multiple tables inter-relates to each other.
- In simple words a Foreign Key is a field in one table that uniquely identifies the field of another table.
- Basically we use foreign to link data of different database tables.
- A table that contains the foreign key is known as referencing or child table.
- Where a table which contains candidate key is known as referenced or parent table.
- A table may contain more than one foreign keys that points to the primary key of different database Table.
- Multiple rows of a child table may refers to the same row of parent table, this relationship between table is called One To One relationship. (See the image below)
Why and when to use Foreign Key?
We know that at any organization, there has to maintain a huge and complex database. There will not be a single database table for storing entire data. Moreover, there may be more than one table which relates to the same entity. So here, we need to relate/ connect data of these different tables which points to same entity. The concept behind it is Foreign Key. With the help of foreign key we can easily connect different database tables.
Let’s take an example, Suppose there is a table for student record which stores student’s data. As shown in image 1 above, student id, first-name, last-name and course-id are their fields. Where course-id is the foreign key i.e refers to the primary key of another table.
We can say that there are two modules, one for storing student information and other for storing course details. There is a field course_id which is responsible for linking tables. It also makes sure that a student must select the available course only (not other).
What is primary key, candidate key and super key?
Sometimes above are very confusing terms for most of the students. Here is the little bit explanation of all above that is enough to understand them:
Primary key is a field in a table, which uniquely identifies the table. A database table must have an primary key which uniquely identifies each row. It remains different for every field i.e a primary key must not be repeat for different objects. For example roll no, employee id are unique fields i.e can not same for two different persons.
In other words we can say that, a primary key is a field in table which is selected to become primary key of another table.
A candidate key is a field in a table, which may uniquely identify it. In other words we can say that a candidate key is a field which is candidate to uniquely identify the table. Sometimes, we need to combine the fields to make a primary key. These fields are called candidate keys.
For example, a table contain names and father’s names. More than one users can have the same name so we can’t take name field as a primary key. But we can combine the name and father’s name fields to uniquely identify each users. The idea behind that is, a user can’t have the same username and father’s name(just assume). You can combine more than one fields to uniquely identify each record of a table.
A super key is a key, which we can create by combining more than one candidate keys. We create super key to uniquely identify a table data.
Syntax for Foreign Key in Django
model_obj = models.ForeignKey(parentTableName, on_delete=models.CASCADE)
- First parameter is the name of the parent table.
- Where second required parameter means that when primary key(parent table) object is deleted from one table, foreign key(child table) of particular row will also delete automatically.
Foreign Key example
firstproject > myapp > models.py
from django.db import models class employee(models.Model): name= models.CharField(max_length=250) Contact= models.IntegerField() email = models.EmailField(max_length=200,unique=True) About = models.TextField() portfolio_site = models.URLField() registered=models.BooleanField() date_of_birth= models.DateField() registered_on= models.DateTimeField(auto_now_add=True) salary = models.DecimalField(max_digits=10,decimal_places=5) membership_valid=models.DurationField() def __str__(self): return repr(self.id) class empArr(models.Model): Emp_id = models.ForeignKey(employee,on_delete=models.CASCADE) Arrival_time = models.DateTimeField() def __str__(self): return repr(self.Arrival_time)
firstproject > myapp > admin.py
from django.contrib import admin from myapp.models import empArr admin.site.register(empArr)
Download source code
So it is all about the foreign keys, if you want to learn other model fields you can visit the link below. Thanks!!!