Introduction of Django Get_or_Create Field
Sometimes there may be scenarios where the object or the value is not passed default. So in these instances, when the value is not passed from the user or upstream, there will be a need to get the value from the source; in case at the instance when the value is not derived from the source, then the value may need to be created. So, in these instances, when the value is expected to be retrieved, the get or create will be used. The get or create method will create the given values when a get does not return any value.
Syntax:
Object_Name = model_name.objects.Get_or_CreateField(values)
The object to be created is placed as the leftmost item. So the leftmost item will be the object. Then the model for which the object needs to be triggered on get or create is placed. The values for the get or create has to be associated in the arguments area. The methods like get or create provide a lot of flexibility in declaring the object and instantiating the value for the object. These are among the advantages of the GetorCreate function.
How Do Get_or_Create Field Works in Django?
The way through which we get or create works is exciting. The get or create involves a get call. The get process will be triggered based on this value. When the initial get() returns the expected value, a tuple will be returned with a Boolean value as false. Multipleobjects returned error will be raised when the call retunes more than one object. When the case of the object not found is raised, then the get_or_create will instantiate a save new object process, returning a tuple and a Boolean value of True. So the new value will be stored as expected, and the get or create will be instantiated.
Create a Django Get_Or_Create Field
Creating a Django Get_Or_Create Field is explained below:
1. Changes in Models.py file
As the syntax section mentions, the Get_or_Create field must be declared in the models.py file. We can notice that the Get_or_Create field is declared as the age field in the model.
(models.py)
from django.db import models
from django.contrib.auth.models import User
# Model variables
# Create your models here.
class Bride(models.Model):
Get_or_create_Example__Example_name = models.CharField(max_length=200,null=True)
Get_or_create_Example__Example_age = models.Get_or_create_Example_Field(null=True)
Get_or_create_Example__Example_thegai = models.CharField(max_length=200,null=True)
Get_or_create_Example__Example_State = models.CharField(max_length=50,null=True)
Get_or_create_Example__Example_District = models.CharField(max_length=50,null=True)
Get_or_create_Example__Example_Address = models.TextField(null=True)
Get_or_create_Example__Example_Phone = models.BigGet_or_create_Example_Field(null=True)
Get_or_create_Example__Example_profession = models.CharField(max_length=200,null=True)
Get_or_create_Example__Example_salary = models.BigGet_or_create_Example_Field(null=True)
Get_or_create_Example__Example_Under_Graduation_Degree = models.CharField(max_length=200,null=True)
Get_or_create_Example__Example_Under_Graduation_college = models.CharField(max_length=400,null=True)
Get_or_create_Example__Example_Post_Graduation_Degree = models.CharField(max_length=200,null=True)
Get_or_create_Example__Example_Post_Graduation_college = models.CharField(max_length=400,null=True)
Get_or_create_Example__Example_Rasi = models.CharField(max_length=200,null=True)
Get_or_create_Example__Example_Nakshatra = models.CharField(max_length=200,null=True)
def __str__(self):
return self.name
2. Changes in Settings.py file
Ensure all of the values and the database connects are set nicely within the settings.py record so the undertaking may be kicked for execution flexibly. The middleware objects stated under must be declared well within the settings.py record because those center wares are chargeable for the functioning of the software at the same time as processing GET and PUT messages. Additionally, the templates used want to cram so that the template processing takes place within the background.
(Settings.py):
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',
],
},
},
]
3. Changes in url.py file
The Media root and document root variables must be instantiated inside the url.py file like below. The changes for the url.py file are mentioned below.
url.py:
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.Get_or_create_Example_page,name='profile'),
url(r'logout/',views.logout_request,name='logout'),
url(r'reg/',views.Get_or_create_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)
3. Create a view for the form
The Get_or_Create 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 given views.py section.
Ex: views.py
@login_required
def Get_or_create_Example_page(request,pk):
dict_to_render = {}
Get_or_create_key_variable_ = Bride.objects.get(id=pk)
Get_or_create_Example_name = Get_or_create_key_variable_.name
Get_or_create_Example_Age = Bride.objects.get_or_create(first_name='Nalandan', last_name='Ranjan',defaults={'birthday': date(1990, 10, 9)})
Get_or_create_Example_Thegai = Get_or_create_key_variable_.thegai
Get_or_create_Example_state = Get_or_create_key_variable_.State
Get_or_create_Example_district = Get_or_create_key_variable_.District
Get_or_create_Example_Address = Get_or_create_key_variable_.Address
Get_or_create_Example_Phone = Get_or_create_key_variable_.Phone
Get_or_create_Example_Profession = Get_or_create_key_variable_.profession
Get_or_create_Example_Salary = Get_or_create_key_variable_.salary
Get_or_create_Example_UG = Get_or_create_key_variable_.Under_Graduation_Degree
Get_or_create_Example_UGC = Get_or_create_key_variable_.Under_Graduation_college
Get_or_create_Example_PG = Get_or_create_key_variable_.Post_Graduation_Degree
Get_or_create_Example_PGC = Get_or_create_key_variable_.Post_Graduation_college
Get_or_create_Example_UG = Get_or_create_key_variable_.Under_Graduation_Degree
Get_or_create_Example_UGC = Get_or_create_key_variable_.Under_Graduation_college
Get_or_create_Example_PG = Get_or_create_key_variable_.Post_Graduation_Degree
Get_or_create_Example_PGC = Get_or_create_key_variable_.Post_Graduation_college
Get_or_create_Example_Rasi = Get_or_create_key_variable_.Rasi
Get_or_create_Example_Nakshatra = Get_or_create_key_variable_.Nakshatra
dict_to_render['Age'] = Get_or_create_Example_Age
dict_to_render['name'] = Get_or_create_Example_name
dict_to_render['thegai'] = Get_or_create_Example_Thegai
dict_to_render['State'] = Get_or_create_Example_state
dict_to_render['district'] = Get_or_create_Example_district
dict_to_render['Address'] = Get_or_create_Example_Address
dict_to_render['Phone'] = Get_or_create_Example_Phone
dict_to_render['profession'] = Get_or_create_Example_Profession
dict_to_render['Under_Graduation_Degree'] = Get_or_create_Example_UG
dict_to_render['Under_Graduation_college'] = Get_or_create_Example_UGC
dict_to_render['Post_Graduation_Degree'] = Get_or_create_Example_PG
dict_to_render['Post_Graduation_college'] = Get_or_create_Example_PGC
dict_to_render['Rasi'] = Get_or_create_Example_Rasi
dict_to_render['Nakshatra'] = Get_or_create_Example_Nakshatra
print(Get_or_create_key_variable_.Creator)
print(dict_to_render)
return render(request,'Profilepage.html',dict_to_render)
4. Formulate an HTML file for displaying the form
Corresponding changes to the HTML pages have to be performed.
Profilepage.html
<!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">
<br>
{% block content %}
{% if Get_or_Create %}
<img src="{{Get_or_Create.url}}" align="right" alt="Get_or_Create" class="img-thumbnail" style="max-height:200px">
{% else %}
<img src="{% static 'admin/img/default.png' %}" align="right" alt="Get_or_Create" class="img-thumbnail" style="max-height:200px">
{% endif%}
<br></br>
<h6><strong>Name :    {{name}}</strong></h6>
<h6><strong>Age :    {{Age}}</strong></h6>
<h6><strong>Thegai :    {{thegai}}</strong></h6>
<h6><strong>State :    {{State}}</strong></h6>
<h6><strong>district :    {{district}}</strong></h6>
<h6><strong>Address :    {{Address}}</strong></h6>
<h6><strong>Phone :    {{Phone}}</strong></h6>
<h6><strong>profession :    {{profession}}</strong></h6>
<h6><strong>Under Graduation Degree :    {{Under_Graduation_Degree}}</strong></h6>
<h6><strong>Post_Graduation_Degree :    {{Post_Graduation_Degree}}</strong></h6>
<h6><strong>Post_Graduation_college :    {{Post_Graduation_college}}</strong></h6>
<h6><strong>Rasi :    {{Rasi}}</strong></h6>
<h6><strong>Nakshatra :    {{Nakshatra}}</strong></h6>
{% endblock content %}
</div>
</script>
</body>
</html>
Output:
Conclusion
The process of how the get or create is instantiated, and the values set for the get or create are declared nicely above. The syntax and the coding changes involved in the get or create method are discussed deeply in the above article with suitable references. All code is produced in a detailed manner.