Introduction of Django Get_or_Create Field
At some instances there may scenarios were the object or the value is not passed default. So at 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, 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 left most item. So the left most 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 provides a lot of flexibility in declaring the object and instantiating the value for the object. These are among the advantages for the GetorCreate function.
How Get or Create Works?
The way through which get or create works is very interesting. Actually the get or create involves a get call basically. The get process will be triggered based on this value. When the initial get() will itself returns the value expected then a tuple will be returned with a Boolean value as false. Multipleobjects returned error will be raised when more than one objects are retuned by the call. When the case of object not found is been raised then the get_or_create will instantiate a save new object process which will be 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
Create a Django Get_Or_Create Field are explain below:
1. Changes in Models.py file
As mentioned in the syntax section the Get_or_Create field needs to 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 withinside the settings.py record in order that the undertaking may be kicked for execution flexibly. The middleware objects stated under must be declared nicely withinside the settings.py record, due to the fact those center wares are chargeable for functioning of the software at the same time as processing GET and PUT messages. Additionally, the templates used has additionally want to crammed in order that the template processing takes place withinside 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 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:
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 under 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 a HTML file for displaying the form
Corresponding changes to the HTML pages has 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 are 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.
Recommended Articles
This is a guide to Django Get_or_Create Field. Here we also discuss the introduction and How Get or Create Works? along with examples. 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