Updated May 20, 2023
Introduction to Django Foreign Key
A foreign key facilitates the flexible utilization of one table’s fields in another table, enabling the easy linking of two different tables. The linking of the two tables is straightforward using foreign key processes. The enforcement of the links between the two tables occurs by utilizing the respective keys. In certain cases, people also refer to the foreign key as a reference key. The Foreign key allows the match between a primary key of a different table. The foreign key field will enable many-to-one relationships from the kind of relationship generated. so more than one table could be flexibly connected with one table on the other end. Foreign keys can effectively establish a relationship between many fields and a single field. It can assign the arguments of the foreign key field within it. So as per the assignation of these field attributes, the foreign key field will operate like this.
Syntax:
Foreignkey name = models.ForeignKey(Table_name, null_argument, Ondelete_arguemnt)
Here the first argument represents a table name. So, in the first argument of the Foreign key model, you can mention the name of the table from which the respective key is borrowed. We need to discuss the table from which the foreign key value is derived. This is the first argument of the method. Next, the null argument mentions the value null associated with the records coming further or already present in the table. Mentioning this record as null enables the existing or new records to be filled with a Null value when no value is specified.
The following argument is the most important argument. This argument decides how the impact of deletion on the staging table needs to impact the parent table. So, when a parent table record is removed, the corresponding record should bear the impact, or the impact can be omitted in the determination here. So based on this determination, the change to the parent table will be accordingly reflected here. Additionally, on the left side of the equation is the name of the foreign key column. This name represents the newly created column’s name. So the name-value given here will be the name of the column further.
Create a Django Foreign Key
How to Create a Django Foreign Key is explained below:
1. Changes in Models.py file
You must declare the foreign key in the models.py file. The example below showcases the foreign key named ‘example_creator.’ Moreover, this field is designated as a foreign key since it references the User table. Additionally, specific attributes are configured, including the allowance of null values and the specification of the ondelete function as CASCADE.
Example:
from django.db import models
from django.contrib.auth.models import User
# Model variables
# Create your models here.
class Bride(models.Model):
Example_name = models.CharField(max_length=200,null=True)
Example_age = models.IntegerField(null=True)
Example_thegai = models.CharField(max_length=200,null=True)
Example_State = models.CharField(max_length=50,null=True)
Example_District = models.CharField(max_length=50,null=True)
Example_Address = models.TextField(null=True)
Example_Phone = models.BigIntegerField(null=True)
Example_profession = models.CharField(max_length=200,null=True)
Example_salary = models.BigIntegerField(null=True)
Example_Under_Graduation_Degree = models.CharField(max_length=200,null=True)
Example_Under_Graduation_college = models.CharField(max_length=400,null=True)
Example_Post_Graduation_Degree = models.CharField(max_length=200,null=True)
Example_Post_Graduation_college = models.CharField(max_length=400,null=True)
Example_Rasi = models.CharField(max_length=200,null=True)
Example_Nakshatra = models.CharField(max_length=200,null=True)
Example_Creator = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.name
2. Changes in Forms.py file
The forms.py file integrates the records of the model into a form. In this case, we specifically perform the integration for the Bride model. So making this inheritance here of the bride model will allow the records of the bride model to be associated with this form page.
Example:
from django import forms
from .models import Bride
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class Valueform(forms.ModelForm):
# Rasi = forms.ChoiceField(choices = Rasi_CHOICES)
class Meta:
model = Bride
fields = "__all__"
3. Create a View for The Form
You should create a Django view that renders the form and includes the middleware for the Foreign Key Field registered in it. Clicking the submit button will save the form. The render function is the first imported item in the Django library. This import process will render the presented HTML file to the browser. After this importing, the HTTP response will be performed. The views method instantiates the expected value Form, which allows for flexible rendering of the form. The instantiation is performed on a form named with a specific value. The save process will take place with the form. Save() method. The form will fetch and store the details of the currently logged-in user. This is how the form storage will take place. After successfully storing the form, you can render it on the browser using the render method.
Example:
def form_view(request):
form = Valueform(request.POST or None)
if form.is_valid():
post = form.save()
post.Creator = request.user
print('Creator user stored',request.user)
post.save()
return render(request,'form.html', {"form": form})
def form_edit(request):
form = Valueform(request.POST or None)
if form.is_valid():
post = form.save()
post.Creator = request.user
print('Creator user updated',request.user)
post.save()
return render(request,'form_edit.html', {"form": form}
def form_update(request):
form = Valueform(request.POST or None)
if form.is_valid():
post = form.save()
post.Creator = request.user
print('Creator user updated',request.user)
post.save()
return render(request,'form_edit.html', {"form": form}
4. Formulate an HTML File for Displaying the Form
You have to perform corresponding changes to the HTML pages.
Form.html
{% block content %}
<form method="POST" class='formarea'>
<div class='formdiv'>
{{ form.as_p }}
{% csrf_token %}
<input type="submit" class='button' value="submit">
</div>
</form>
{% endblock content %}
Output:
Conclusion
This article depicts how you can flexibly declare the foreign key in a Django setup, how you can render the changes to a form item, and how you can pass the input values. You can create an unlimited number of foreign key connections in an application. Moreover, the models of a Django setup allow maintaining these fields very sophisticatedly without any vast changes applied in the database. This is the major advantage of the Django setup.
Recommended Articles
We hope that this EDUCBA information on “Django Foreign Key” was beneficial to you. You can view EDUCBA’s recommended articles for more information.