Horje
How do we Get the Object if it Exists, or None if it Does Not Exist in Django?

In Django, querying the database is a fundamental part of building web applications. Often, you need to retrieve an object from the database if it exists or return None if it does not. This article will guide you through creating a simple Django project to demonstrate this functionality.

We’ll cover the following steps:

  • Setting up a Django project.
  • Creating a single-page application.
  • Querying the database to get an object or None.

How do we Get the Object if it Exists, or None if it Does Not Exist in Django?

Step 1: Install Django

If you don’t have Django installed, you can install it using pip:

pip install django

Step 2: Create a New Django Project

Create a new Django project by running the following command:

django-admin startproject myproject
cd myproject

Step 3: Create a Django App

Create a new app within your project:

python manage.py startapp myapp

Add the new app to your project’s settings. Open myproject/settings.py and add ‘myapp’ to the INSTALLED_APPS list:

INSTALLED_APPS = [
# other installed apps
'myapp',
]
f3

Step 5: Create a Model

In myapp/models.py, define a simple model. For this example, we’ll create a Person model:

Python
from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(unique=True)

    def __str__(self):
        return self.name

Run the following commands to create the necessary database tables for the new model:

python manage.py makemigrations myapp
python manage.py migrate

Create the superuser using below command and add the data in database.

python manage.py createsuperuser

Step 6: Create a View

In myapp/views.py, create a view to handle the Object if it Exists, or None if it Does Not Exist logic:

This Django view consists of two functions. The index function handles POST requests to search for a Person by email. It retrieves the email from the request, uses the get_person_by_email function to find the Person object, and passes it to the context for rendering in the index.html template. The get_person_by_email function tries to fetch a Person by email from the database, returning the Person object if found, or None if not.

Python
from django.shortcuts import render
from .models import Person

def index(request):
    context = {}
    if request.method == 'POST':
        email = request.POST.get('email')
        person = get_person_by_email(email)
        context['person'] = person

    return render(request, 'index.html', context)

def get_person_by_email(email):
    try:
        return Person.objects.get(email=email)
    except Person.DoesNotExist:
        return None

Step 7: Create a Template

Create a template file index.html in myapp/templates/:

HTML
<!DOCTYPE html>
<html>
<head>
    <title>Get Person by Email</title>
</head>
<body>
    <h1>Find Person</h1>
    <form method="POST">
        {% csrf_token %}
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <button type="submit">Search</button>
    </form>

    {% if person %}
        <p>Person found: {{ person.name }} ({{ person.email }})</p>
    {% else %}
        <p>No person found with that email.</p>
    {% endif %}
</body>
</html>

Step 8: Configure the URL

In myapp/urls.py, define a URL pattern for the view:

Python
from django.urls import path
from .views import index

urlpatterns = [
    path('', index, name='index'),
]

Include the app’s URLs in the project’s urls.py:

Python
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
]

Running the Project

Run the development server to see your single-page application in action:

python manage.py runserver

Open your web browser and navigate to http://127.0.0.1:8000/. You should see a form where you can enter an email address. If the email corresponds to an existing Person object in the database, their details will be displayed. Otherwise, a message indicating no person was found will be shown.

res1res2

Conclusion

In this article, we covered how to set up a simple Django project and create a single-page application that retrieves a Person object by email or returns None if it does not exist. This approach is useful for various scenarios where you need to query the database conditionally. With Django’s powerful ORM and handling of exceptions, you can efficiently manage such tasks in your web applications.




Reffered: https://www.geeksforgeeks.org


Python

Related
How to Fetch All Rows with psycopg2.fetchall in Python How to Fetch All Rows with psycopg2.fetchall in Python
Convert Django Model Object to Dict with all of the Fields Intact Convert Django Model Object to Dict with all of the Fields Intact
Can &quot;list_display&quot; in a Django ModelAdmin Display Attributes of ForeignKey Fields? Can &quot;list_display&quot; in a Django ModelAdmin Display Attributes of ForeignKey Fields?
How to Install python-dotenv in Python How to Install python-dotenv in Python
Set a Default Value for a Field in a Django Model Set a Default Value for a Field in a Django Model

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
22