Users Online

· Guests Online: 54

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Articles Hierarchy

Django Tutorial

Django Foreign Key

Django Foreign Key

Introduction to Django Foreign Key

A foreign key is a process through which one table’s fields can be used flexibly in another table. So, two different tables can be easily linked using the foreign key. This linking of the two tables can be easily achieved using foreign key processes. It will be enforced to allow links between two tables using the keys involved. The foreign key is also mentioned as a reference key in some cases. The Foreign key allows the match between a primary key of a different table. From the kind of relationship generated, the foreign key field will allow many to one relationship. so more than one table could be flexibly connected with one table on the other end. So this sought of many fields to one single field can be effectively raised using foreign keys. The arguments of the foreign key field can be assigned 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 the name of the table assigned as the first argument of the Foreign key model allows mentioning the table from which the respective key is borrowed. So the table from which the foreign key value is taken will be mentioned here. 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 allows the records already behind or new records added to be filled with a Null value when no value is mentioned for it.

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 here 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 mentions the name of the column which is newly created. So the name-value given here will be the name of the column further.

Create a Django Jsonfield

How to Create a Django Jsonfield is explained below:

1. Changes in Models.py file

The foreign key has to be declared in the modelys.py file, IN the below example, we can notice the foreign key is mentioned as example_creator. Moreover, this field is declared as a foreignkey because its values are integrated from the original table User. Additionally, properties like associating the null value as True and the ondelete function are made with 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 records of the model are integrated to a form in the forms.py file. Here the integration of the model Bride is performed. So making this inheritance here of the bride model will allow the records of the bride model to be associated to 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

A Django view desires to be formed to make the middleware for the form through the Foreign key Field registered in it to be rendered. Clicking the submit button will save the form. The render function is the first imported item in the Django library. This import process will allow the HTML file to be rendered to the browser which is presented. After this importing, the HTTP response will be performed. The expected value Form is instantiated in the views method, which fatherly allows the form to be flexibly rendered. The instantiation will be performed on a value-named form. The save process will take place with the form. Save() method. Then the currently logged-in user details will be fetched and stored on the form. This is how the form storage will take place. After the form is successfully stored, it will be rendered onto the browser with a 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

Corresponding changes to the HTML pages have to be performed.

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:

Django Foreign Key

Conclusion

This article depicts how the foreign key can be flexibly declared in a Django setup, how the changes can be rendered to a form item, and how the input values can be passed from there on. There is no limit on the number of foreign key connections created 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.

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.81 seconds
10,842,761 unique visits