Django Foreign Key

Learn via video courses
Topics Covered

Overview

A foreign key is a distinct flexible field in Django's model since it is used to join or link two tables together. It will be required to permit connections between two tables using the relevant keys. Sometimes, the foreign key is also specified as a reference key. It reduces the repetition of code and increases the usability and association of data. In this tutorial, we'll talk deeply about Django's foreign key and understand how it works and how can we use it efficiently.

Introduction to Django Foreign Key

A foreign key allows for the flexible use of fields in Django's model from one table to another table. So, using a foreign key to connect two separate tables is simple. By using foreign key procedures, it is simple to connect the two tables i.e two separate models in the Djangthe o application. It will be required to permit connections between two tables using the relevant keys. In some instances, the foreign key is also specified as a reference key. Django foreign key allows the main key from a separate table to match. The foreign key field will allow many-to-one relationships depending on the type of relationship generated to flexibly connect multiple tables with a single table at the other end. Therefore, using foreign keys can effectively raise this request to reduce multiple fields to a single field. It allows the assignment of the foreign key field's arguments.

Syntax

The first argument in this case represents a table name. As a result, the Foreign key model's first argument is the name of the table that allows that table/model to share keys/data and relationship with this Foreignkey_name table/model. As a result, we'll mention the table where the foreign key value was obtained. The method's opening justification is this. The null argument is then used to specify the value null to be linked to records that will be added to the table later or that are already there. When no value is specified for it, mentioning this record as null allows any existing or future records to be filled with a value of NULL.

The most crucial argument comes after that. This option determines how the parent table must be affected by the deletion of the Foreignkey_name table. The decision here is whether or not the matching record here should incur the impact of the removal of a parent table record. The modification to the parent table will therefore be appropriately recorded here based as stated above. The name of the foreign key column is also shown on the left side of the equation. This name contains the name of the recently created column. The name of the column will therefore be determined by the name-value pair provided here.

Create a Django Jsonficoncerningt to Foreign Key

  • Using your command prompt

To make a directory name example

Check python version

To install python environment

To install Django

Create DjangDjangoect name example_project

Move to example_project directory

Create a Django app inside example_project named example_app

  • Setup settings and project necessary set-up
  • In your models.py add the required models The modelys.py file must contain a declaration of the foreign key. In the example below, the foreign key is identified as example_manager. Additionally, this field is marked as a foreign key because the values it contains are taken from the original User table. It also has other attributes like associating the null value with True and using CASCADE for the on_delete method.
  • Changes in Forms.py file

In the forms.py file, the model's records are integrated with a form. The model Candidate's integration is carried out here. Making the Candidate model inheritable here will therefore enable the Candidate model records to be linked to this form page.

  • Create a View for The Form

A Django view is intended to be created to create the middleware for the form's registered Foreign key Field to be presented. The form will be saved when the submit button is clicked. The Django library's render function is the first imported component. The HTML file can be rendered for the presented browser thanks to this import process. The HTTP response will then be executed after this. The anticipated value Form is instantiated in the views method, which enables the form to be presented flexibly. A value-named form will be used for the instantiation. The form will be saved simultaneously with the process. Save() technique. The details of the user who is currently logged in will then be retrieved and saved on the form. The form storing will happen in this manner. The form will be rendered onto the browser using a render function after being successfully saved.

  • Formulate an HTML File for Displaying the Form

django. db.models ForeignKey Examples

Django Foreign key is a field-to-column integration for creating and associating relations between multiple tables to share properties and attributes of one another(models/tables). Although ForeignKey is defined in the django.db.models.related module, most references to it come from django.db.models instead of the reference to the related module.

From AuditLog

A reusable app for Django, django-auditlog (Auditlog), simplifies the process of logging object modifications. To minimize the number of dependencies, Auditlog uses as much of Python and Django's built-in capabilities as feasible. Additionally, Auditlog promises to be quick and easy to use.

The need for a straightforward Django application that records model changes together with the user who performed the changes led to the creation of Auditlog (later referred to as actor). Existing methods appeared to provide a sort of version control, but performance and database storage costs were deemed excessive and expensive.

Example:

From Django-Allauth

A reusable Django application that offers simple flows for both local and social authentication is called django-allauth.It supports a variety of account verification methods and authentication mechanisms, such as login by user name or email. To enable you to publish wall updates and other content, all access tokens are continually stored. The Pluggable registration forms allow for the inclusion of questions. It supports linking a Django user account to numerous social media accounts. Through the Django admin and the SocialApp model, the necessary consumer keys and secrets for communicating with Facebook, Twitter, and other services must be configured in the database.

Example: django-allauth / allauth / socialaccount / models.py

From Django-Guardian

By extending the current authentication backend, Django-guardian gives per-object permissions in Django projects. In simple words, Django-guardian gives authentication and permission restrictions to every object of a Django application.

Example: django-guardian / guardian / migrations / 0001_initial.py

Conclusion

The above tutorial makes evident how the foreign key may be flexibly specified in a Django setup, how the changes can be made to a form item, and how the input values can then be sent from that point on. It also provides helpful examples to demonstrate how to use and use Django’s foreign key. This tutorial shows

  • A foreign key allows for the flexible use of fields in Django’s model from one table to another table to connect two separate tables is simple.
  • There is no restriction on how many foreign key connections can be established in a single application.
  • Also a proper example of how foreign keys are used and implemented above.
  • We saw ForeignKey examples of AuditLog, Django-allAuth, and Django-guardian models.