Introduction to Django one to many
One to many is a situation where one field is pointed to more than one field. So, one specific field will be pointing to more than one fields in the database. This relational correlativity will lead to one-to-many relationships in Django. Basically, Django doesn’t not have any default built-in fields in Django to support one to many relationships. This field combination is achieved by means of the statement foreignkey in Django. So foreignkey statement is used to support the correlation of one-to-many statements in Django. Here columns from one table can be extended in connection with more than one column in various other tables.
Syntax:
Object_Name = model_name.ForeignKey(Table_name, null_argument, Ondelete_arguemnt)
How does one to many Works?
- Here the primary argument represents a table call. So this call of the table is assigned because the first argument of the Foreign key version permits to say the table from which the respective secret is borrowed from. So the table from which the overseas key cost is taken from might be noted right here. This is the primary argument of the method. Next, the null argument is used to say the cost null to be related to the data coming in addition or already gift withinside the table. Mentioning this document as null permits, the data already in the back of or new data brought to be full of null cost whilst no cost is noted for it.
- The subsequent argument is the maximum vital argument. This argument comes to a decision on how the effect of deletion at the staging table wants to affect the distinguish table. So, whilst table data are eliminated, the corresponding document right here needs to undergo the effect, or the effect may be overlooked. So, based on this, the alternate to the distinguish table might be considered right here. Additionally, at the left facet of the equation is the call of the overseas key column. This call mentions the call of the column that’s newly created. So the call cost given right here might be the call of the column further.
Create a Django one to many Field
Given below shows creation of Django one to many field:
1. Changes in Models.py file
As mentioned in the syntax section, the one-to-many field must be declared in the models.py file. We can notice that the one to many field is declared as the age field in the model.
(models.py):
Code:
from django.db import models
from django.contrib.auth.models import User
# Model variables
# Create your models here.
class Bride(models.Model):
OnetoMany_Example_name = models.CharField(max_length=200,null=True)
OnetoMany_Example_thegai = models.CharField(max_length=200,null=True)
OnetoMany_Example_State = models.CharField(max_length=50,null=True)
OnetoMany_Example_District = models.CharField(max_length=50,null=True)
OnetoMany_Example_Address = models.TextField(null=True)
OnetoMany_Example_Phone = models.BigOnetoMany_Example_Field(null=True)
OnetoMany_Example_profession = models.CharField(max_length=200,null=True)
OnetoMany_Example_salary = models.BigOnetoMany_Example_Field(null=True)
OnetoMany_Example_Under_Graduation_Degree = models.CharField(max_length=200,null=True)
OnetoMany_Example_Under_Graduation_college = models.CharField(max_length=400,null=True)
OnetoMany_Example_Post_Graduation_Degree = models.CharField(max_length=200,null=True)
OnetoMany_Example_Post_Graduation_college = models.CharField(max_length=400,null=True)
OnetoMany_Example_Rasi = models.CharField(max_length=200,null=True)
OnetoMany_Example_Nakshatra = models.CharField(max_length=200,null=True)
OnetoMany_Example_Creator = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
def _str_(self):
return self.name
2. Changes in Forms.py file
Below are the changes associated to the forms.py file. The changes mention to add the table bride in this forms.py file. So what happens is all the fields from the table will be getting associated here by declaring them in forms.py file.
Ex: (forms.py):
Code:
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. Changes in Settings.py file
Ensure all of the values and the database connects are set nicely withinside the settings.py record in order that the undertaking may be kicked for execution flexibly.
(Settings.py):
Code:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Matrimony.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [Template_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'render_dict_processors': [
'django.template.render_dict_processors.debug',
'django.template.render_dict_processors.request',
'django.contrib.auth.render_dict_processors.auth',
'django.contrib.messages.render_dict_processors.messages',
],
},
},
]
4. Changes in url.py file
The media root and document root variable need to be instantiated inside the url.py file as like below.
The changes for the url.py file are mentioned below.
url.py:
Code:
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from matrimony_pages import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$',views.Welcome_page,name='Welcome_page'),
url(r'Mainpage/',views.Main_page,name='Main_page'),
url(r'form/',views.form_view,name='form_view'),
url(r"signup/", views.Sign_up_request, name="register"),
url(r"login/", views.login_request, name="login"),
path(r'profile/<str:pk>/',views.OnetoMany_Example_page,name='profile'),
url(r'logout/',views.logout_request,name='logout'),
url(r'reg/',views.OnetoMany_Example_reg_user,name='reg'),
path(r'update/<str:pk>/',views.form_update,name='update'),
path('admin/', admin.site.urls),
]+ static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
5. Create a view for the form
The one to many fee while submitted must be saved, and while retrieved, it must be pulled from the database. This may be executed through the item created for the model. The manner of doing that is defined withinside the under given views.py section.
Ex: views.py:
Code:
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})
@login_required
def OnetoMany_Example_page(request,pk):
rendering_dict = {}
OnetoMany_key_variable_ = Bride.objects.get(id=pk)
OnetoMany_Example_name = OnetoMany_key_variable_.name
OnetoMany_Example_Age = Bride.objects.OnetoMany(first_name='Nalandan', last_name='Ranjan',defaults={'birthday': date(1990, 10, 9)})
OnetoMany_Example_Thegai = OnetoMany_key_variable_.thegai
OnetoMany_Example_state = OnetoMany_key_variable_.State
OnetoMany_Example_district = OnetoMany_key_variable_.District
OnetoMany_Example_Address = OnetoMany_key_variable_.Address
OnetoMany_Example_Phone = OnetoMany_key_variable_.Phone
OnetoMany_Example_Profession = OnetoMany_key_variable_.profession
OnetoMany_Example_Salary = OnetoMany_key_variable_.salary
OnetoMany_Example_UG = OnetoMany_key_variable_.Under_Graduation_Degree
OnetoMany_Example_UGC = OnetoMany_key_variable_.Under_Graduation_college
OnetoMany_Example_PG = OnetoMany_key_variable_.Post_Graduation_Degree
OnetoMany_Example_PGC = OnetoMany_key_variable_.Post_Graduation_college
OnetoMany_Example_UG = OnetoMany_key_variable_.Under_Graduation_Degree
OnetoMany_Example_UGC = OnetoMany_key_variable_.Under_Graduation_college
OnetoMany_Example_PG = OnetoMany_key_variable_.Post_Graduation_Degree
OnetoMany_Example_PGC = OnetoMany_key_variable_.Post_Graduation_college
OnetoMany_Example_Rasi = OnetoMany_key_variable_.Rasi
OnetoMany_Example_Nakshatra = OnetoMany_key_variable_.Nakshatra
rendering_dict['Age'] = OnetoMany_Example_Age
rendering_dict['name'] = OnetoMany_Example_name
rendering_dict['thegai'] = OnetoMany_Example_Thegai
rendering_dict['State'] = OnetoMany_Example_state
rendering_dict['district'] = OnetoMany_Example_district
rendering_dict['Address'] = OnetoMany_Example_Address
rendering_dict['Phone'] = OnetoMany_Example_Phone
rendering_dict['profession'] = OnetoMany_Example_Profession
rendering_dict['Under_Graduation_Degree'] = OnetoMany_Example_UG
rendering_dict['Under_Graduation_college'] = OnetoMany_Example_UGC
rendering_dict['Post_Graduation_Degree'] = OnetoMany_Example_PG
rendering_dict['Post_Graduation_college'] = OnetoMany_Example_PGC
rendering_dict['Rasi'] = OnetoMany_Example_Rasi
rendering_dict['Nakshatra'] = OnetoMany_Example_Nakshatra
print(OnetoMany_key_variable_.Creator)
print(rendering_dict)
return render(request,'Profilepage.html',rendering_dict)
6. Formulate a HTML file for displaying the form
Corresponding changes to the HTML pages has to be performed.
Profilepage.html:
Code:
<!DOCTYPE html>
<html style="font-size: 16px;">
<head>
<title>Profile</title>
</head>
<body class="body">
<nav class='navbar'>
<div class='navbar_div'>
<a class="navbar" onclick="redirect2()" >Home </a>
<a class="navbar" onclick="redirect2()" >Contact</a>
<a class="navbar" onclick="redirect1()" >Profiles</a>
</div>
</nav>
<div class="formarea">
{% 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 %}
</div>
</script>
</body>
</html>
Output:
Conclusion
The above given process mentions how to declare one to many field combinations in Django; the syntax of the same is discussed along with the process of how the one to many relationships works in Django. A live website example is also provided, along with snaps from the website. Finally, changes to all the Django related files are discussed above.
Recommended Articles
This is a guide to Django one to many. Here we discuss the introduction, how one to many works? and create a Django one to many field. You may also have a look at the following articles to learn more –
2 Online Courses | 2 Hands-on Projects | 14+ Hours | Verifiable Certificate of Completion
4.5
View Course
Related Courses