Updated May 20, 2023
Introduction of Django Get_or_Create Field
Sometimes, there may be scenarios where the object or the value is not passed as default. In these instances, when the user or upstream does not pass the value, you will need to retrieve the value from the source. If the value is not derived from the source, you may need to create it. So, in these instances, when the value is expected to be retrieved, we use the get or create method. 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)
Place the object to be created as the leftmost item. So the leftmost item will be the object. Then place the model that needs to trigger the object on get or create. 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 to 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. This value triggers the get process. When the initial get() returns the expected value, it replaces it with a tuple containing a Boolean value of false. It raises an error if it returns multiple objects. In the case of the object not found, get_or_create initiates the process of saving a new object and returns a tuple with 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
Below is an explanation of how to create a Django Get_Or_Create Field:
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 observe that the age field in the model is declared as the Get_or_Create field.
(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
Please ensure that you properly set all values and database connections within the settings.py file to allow flexible execution of the project. Declare the middleware objects correctly in the settings.py file because these middlewares are responsible for handling the application’s functioning when processing GET and PUT messages. Additionally, the templates used want to cram so that the template processing occurs 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
Instantiate the Media root and document root variables inside the url.py file as follows. Please make the changes to the url.py file as 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
While submitting, the Get_or_Create fee must save, and while retrieving, it must pull from the database. You can execute this through the item created for the model. The views.py section defines the way to do that.
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
You need to make corresponding changes to the HTML pages.
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 above article nicely explains the process of instantiating the get or create method and declaring the values to set for get or create. It provides a deep dive into the syntax and coding changes involved in the get or make method, offering detailed code examples and suitable references.
Recommended Articles
We hope that this EDUCBA information on “Django Get_or_Create Field” was beneficial to you. You can view EDUCBA’s recommended articles for more information.