Django ORM

Django is a Python web framework that enables easy and quick web development. Django has a handy and powerful feature called Django Object Relational Mapper, also known as Django ORM, which helps us to query or retrieve databases much like SQL or MongoDb. It is mainly used to communicate between the relational database and the user application. The ORM is automated, so the user does not have to write any SQL.

ORM has many advantages, some of which are

  • It provides speedy development
  • It is easier to change the database from ORM
  • It resolves the issue of learning the different SQL for every database

Since web development needs many technologies, it is hard for a developer to learn everything, especially SQL, since it can become very complicated sometimes. ORM solves this issue by creating a database schema from different classes. It saves the user from writing code in many different databases like SQL, PostgreSQL and lets him write code in the only language, i.e., Python.

To demonstrate first, we have to make a Django model:

from Django. db import models
 
 class Student(models.Model):
  name = models.CharField(max_length=100)
    class = models.CharField(max_length = 100)
 
   def __str__(self):
     return self.name
 
 class Project(models.Model):
  title = models.CharField(max_length=100)
  concept = models.CharField(max_length=100)
    author = models.ManyToManyField(Student, related_name="projects")
 
 
   def __str__(self):
     return self.title

We have created two models, Student, and Project. Both have two fields inside them.

The Student has a name and class field, while Project has a title and concept. It also has an author field which is a Many to Many Field that links Project and Student.

To access the Django ORM run the following command in the project library:

python manage.py shell

It opens a console, and now we have to import our model here to use it

For that write:

from blog. models import *

Now let’s start by adding an object to our model.

To create and save and object use the command below:

obj = Student(name = "Rahul", class= "eleventh")
obj.save()

In this, we created a Student object, now to create a Project object, we have to write.

Obj1 = Project(title = “relative motion”, concept = “relativity theory”,author = “Gaurav”)
Obj1.save()

Let us add some more Student objects for demonstration purpose

obj = Student(name = "Mudit", class= "eleventh")
obj.save()
obj = Student(name = "Gaurav", class= "twelfth")
obj.save()

After adding the object, the task is to retrieve them, and this can be done by using objects.all() function

Let’s retrieve the list of all students

Student.objects.all()

It fetch a Queryset of results that lists all the Student

<QuerySet [<Student: Rahul>, <Student: Mudit>, <Student: Gaurav>]>

We can also fetch a single query instead of all by using utility functions like getting (), filter() for that we need a primary key. In this case, we will use the class, but many students are in the same class, so it is not advisable to do so. What we should do is to have an ID for every record.

Student.objects.get(class="twelfth")
<QuerySet [<Student: Gaurav>]>

We can also use the filter function

Student.objects.filter(filter="Rahul")
<QuerySet [<Student: Rahul>]>

To get an interactable python object we can use:

Std = Student.objects.get(class="twelfth")
Std.name
U “Gaurav “

Now we can get all the projects made by this Student to check what projects our Students have made.

Std.projects.all()
<QuerySet[<Project: “Relative motion”>, …… ]>

Modifying Objects

We can also modify an object using ORM as shown

Obj = Student.objects.get(class = “twelfth”)
Obj.name = “Rohan”
Obj.save()

Deleting Objects

To delete an Object we can write:

Obj = Student.objects.get(class = “eleventh”)
Obj.delete()
Student.objects.all() <QuerySet[<Student: Rohan>]>

Related Topics

Django CMS vs WordPress

Both Django CMS and WordPress belong "Self-Hosted Blogging" or "Content Management System (CMS)" category, that is used to manage digital content. Bloggers usually use these platforms. Django CMS Django is one of...

4 minutes read.

Django MVT

 MVT(Model View Template) MVT means Model View Template is a software design pattern The View is used to implement the business logic and to communicate with a model for data transmission and to...

2 minutes read.

How to create an app in Django

Create an application in Django Django is famous for its unique and fully managed application structure. For each functionality, an application can be created as a completely independent module. This article will take...

2 minutes read.

Life Cycle of Django

Life Cycle of Django Request - Response life cycle in Django  Thebasic principle of http protocol is the client sends a request to the server based on the request data, and the server sends...

3 minutes read.

Django REST Framework

Django REST Framework (DRF)is an open-source, powerful, and flexible toolkit used to build RESTful web APIs. It is built upon the Django framework. DRF increases the development speed. Django and...

4 minutes read.

Django Admin

To manage the content of the website, e.g., adding and deleting posts, web developers need an admin portal on the website. The admin portal allows trusted users, also knows as...

3 minutes read.

How to connect Django with Mysql

Any web application contains some data that comes from the input of the end-users. Thus, the database is required to handle those data. Several databases could be used to connect...

3 minutes read.

How to Uninstall Django from cmd

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Django Class Based Views

Class-based views were developed to solve the problem of customizing function-based generic views. We can arrange our view code Object-Oriented by using class views. Class-based views do more than function-based...

3 minutes read.

Creating View in Django

Creating View in Django    Django views are a key component of the frameworkbased applications.We are using Python function or class at their simplest, which takes up a web query and returns a web response.Views are used to get objects from the server, change objects if needed, render types, return HTML, and much more. Class Based View and Function based Django has two types of views: views based on functions (FBVs) and views based on class (CBVs).Initially, Django began with only FBVs, but then introduced CBVs as a way to model features so we didn't have to write boilerplate (i.e. the same software) code again and again.CBVs would be a way to increase efficiency, so you don't have to write as much code as you can. CBVs are classes of Python at their heart. Django ships with a range of "model" CBVs with pre-configured features that can be reused and often expanded.Then helpful names are given to these classes that explain what kind of functionality they provide.These are often referred to as "universal views" because they provide solutions to specific needs. The classes have a journal View function, or "view" for short, is simply a Python program that uses a web query and returns a web response. This response may include the HTML content of a web page, or a redirect, or a 404 error, or an XML file, or an image, etc. Example: You use a view to create a web page, remember that you need to connect a view to a URL to see it as a web page. Simple View We will create a simple view in myapplication to say “Welocome to django application” See the following view – from django.http import HttpResponse ...

4 minutes read.

How to Implement Multiple User Types with Django

Django Framework: Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the...

3 minutes read.

What is Django?

What is Django? Django is a free and open-source web application framework, written in Python. A web framework is a set of components that help you develop an easier and faster website. When we...

3 minutes read.

Django All Auth

For any web application, user registration and authentication are the essential parts. In Django, there are several applications like django-registration-redux to perform these tasks, but the major drawback is that...

6 minutes read.

Django Filters

Django is a high-level python based web framework. Django is mostly used as a backend engine for websites. Nowadays, every website communicates to a database to fetch all the information...

3 minutes read.

Django Messages

Django Framework Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the...

6 minutes read.

Django CMS

Django is one of the most popular open-source Python web development framework. Developers use Django to build a website from scratch. Like WordPress, Django CMS is also a Content Management...

9 minutes read.

Django and React

This article will discuss the overview of Django and React, their advantages, applications, and most importantly, how to implement react in Django. What is Django? Django is a free and open-source web...

6 minutes read.

Django Model Fields

In Django, if we want to store the information about anything, we use Models. It contains various fields about the data. Generally, each model represents a database where all the...

4 minutes read.

Django Logging

Every application developed has some bugs and errors. It is the responsibility of the developers to maintain the application by making it bug-free and error-free. To debug the application code...

5 minutes read.

Django CSRF

Django is a high-level python based web framework. Django is open source and free to use for all. Django provides many features to web developers like scalability, security, rapid development,...

4 minutes read.