What is Foreign Key, Many to Many relationship in Django models? And when should you use one?
When learning through online tutorials, the hardest part has to be how to make sense of everything that is being explained. The answer is to practice it and make your own definitions/sense of it. I know Practice is a word pushed on everyone. But trust me, any company, person, developer, or anyone who has achieved anything, has done so because of their diligence in practice. Enough of philosophy. Let's get to some code.
Foreign Key relationship
Side note: Avoid using too many foreign keys as they can clutter your model and if not handled properly, deleting any foreign key can delete the instance of your mapped data. Remember models.CASCADE, it does it's job diligently.
1. Using foreign key when there is a direct relationship.
Figure 1
In the above example the country model has a foreign key to the president model. In simple words, a country can have only a single president. And the president should be alive (foreign key should exist), otherwise he can't be elected. Duh :) Other example where this type of foreign key relationship can be used is:
- Manufacturer/Product model. A product (ex: iPhone) can have only a single manufacturer (Apple).
2. Creating a foreign key as per demand.
Figure 2
In the above example, we don't want to store phone numbers without any contact information. And we want to store multiple phone numbers that have connection to only a single contact. Compare that to if we created a contact model and had a foreign key to the phone model like below:
Figure 3
This would limit us to have only a single phone number mapped to our contact. So as per our need, we need to follow the code in figure 2.
Other example where this type of foreign key relationship can be used is:
- Contacts/Email model. A contact can have one or more emails.
Many to Many relationship
The Django documentation does a great job at explaining them. Let me just put it in my words. A group can have several people in it. The only pre-requisite is that all of these people should exist in the database.
Figure 4
Above code is obtained from docs.djangoproject.com/en/3.1/ref/models/fi..
Other examples where this type of many-to-many key relationship can be used is:
- Tags/Product model. A product can have multiple tags attached to it.
That's it guys.
If you feel if there's any error in this blog, or you appreciate what I have written, please let me know on Twitter. Also, I am new to twitter so I will appreciate if you can follow me there.