Foreign Key

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.

foreign key
foreign key

Important Points

  • 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)
Foreign Key
Foreign Key

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.

Example

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

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.

Candidate Key

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.

Super Key

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)

Output

Foreign Key
Foreign Key

Download source code

Download project on Github
Download project on Github 

So it is all about the foreign keys, if you want to learn other model fields you can visit the link below. Thanks!!!

Django model fields

29 thoughts on “Foreign Key

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. naturally like your web-site but you have to test the spelling on several of your posts. Many of them are rife with spelling problems and I in finding it very bothersome to inform the reality on the other hand I will certainly come back again.

  2. I have been exploring for a little bit for any high-quality articles or blog posts on this sort of area . Exploring in Yahoo I finally stumbled upon this web site. Reading this information So i am happy to show that I’ve an incredibly just right uncanny feeling I found out exactly what I needed. I such a lot surely will make certain to do not fail to remember this website and provides it a glance regularly.

  3. Heya i’m for the primary time here. I came across this board and I in finding It really helpful & it helped me out a lot. I hope to offer one thing back and help others like you helped me.

  4. Hmm is anyone else experiencing problems with the pictures on this blog loading? I’m trying to figure out if its a problem on my end or if it’s the blog. Any responses would be greatly appreciated.

  5. Oh my goodness! an amazing article dude. Thanks However I am experiencing situation with ur rss . Don’t know why Unable to subscribe to it. Is there anybody getting an identical rss drawback? Anybody who knows kindly respond. Thnkx

  6. hello there and thank you for your info – I have certainly picked up something new from right here. I did however expertise several technical issues using this site, since I experienced to reload the web site a lot of times previous to I could get it to load properly. I had been wondering if your web host is OK? Not that I am complaining, but slow loading instances times will often affect your placement in google and can damage your quality score if ads and marketing with Adwords. Well I am adding this RSS to my email and can look out for a lot more of your respective interesting content. Make sure you update this again very soon..

  7. Wonderful work! This is the kind of information that should be shared across the internet. Disgrace on the search engines for now not positioning this publish higher! Come on over and consult with my website . Thank you =)

  8. Great ¡V I should definitely pronounce, impressed with your site. I had no trouble navigating through all the tabs and related info ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Reasonably unusual. Is likely to appreciate it for those who add forums or anything, site theme . a tones way for your client to communicate. Nice task..

  9. Good website! I really love how it is easy on my eyes and the data are well written. I’m wondering how I could be notified when a new post has been made. I’ve subscribed to your RSS which must do the trick! Have a great day!

  10. My spouse and i got now thrilled when Louis managed to carry out his inquiry out of the precious recommendations he received through the site. It’s not at all simplistic to simply choose to be releasing facts which usually many people may have been making money from. Therefore we know we now have the website owner to appreciate because of that. These illustrations you’ve made, the straightforward website navigation, the friendships you help to create – it’s many excellent, and it’s really aiding our son and the family imagine that this article is amusing, and that is exceedingly mandatory. Many thanks for all!

  11. certainly like your web-site but you need to take a look at the spelling on quite a few of your posts. Several of them are rife with spelling problems and I in finding it very bothersome to tell the truth nevertheless I will certainly come again again.

  12. Good ¡V I should certainly pronounce, impressed with your website. I had no trouble navigating through all tabs as well as related information ended up being truly simple to do to access. I recently found what I hoped for before you know it at all. Reasonably unusual. Is likely to appreciate it for those who add forums or something, website theme . a tones way for your customer to communicate. Excellent task..

  13. I intended to compose you that very little observation in order to say thanks over again for your lovely suggestions you have featured here. It’s really particularly open-handed of you to make extensively precisely what most of us would’ve offered for sale as an ebook to make some profit for themselves, specifically considering that you might well have tried it in the event you decided. These tricks additionally served to provide a great way to realize that other individuals have the same passion the same as my very own to find out significantly more with respect to this condition. I am certain there are a lot more pleasant situations ahead for many who read through your website.

  14. I’m now not positive where you’re getting your info, but good topic. I must spend a while learning more or figuring out more. Thank you for wonderful information I used to be in search of this info for my mission.

  15. I just want to say I am just beginner to weblog and actually enjoyed this web-site. Very likely I’m going to bookmark your blog post . You really come with beneficial writings. Thanks a lot for sharing your web-site.

  16. The the very next time Someone said a blog, I hope it doesnt disappoint me as much as this place. Come on, man, Yes, it was my choice to read, but I actually thought youd have something interesting to express. All I hear is actually a few whining about something that you could fix when you werent too busy in search of attention.

  17. I believe that is one of the such a lot significant info for me. And i’m satisfied reading your article. However want to statement on some common things, The website style is perfect, the articles is really great . Excellent activity, cheers.

  18. Just wish to say your article is as surprising. The clarity in your post is just spectacular and i could assume you’re an expert on this subject. Well with your permission let me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please carry on the enjoyable work.

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.