ORM : Object Relational Mapping

Vaibhav JadhavVaibhav Jadhav
2 min read

Object-oriented programming languages use Object Relation Mapping (ORM) to interact with Structured Query Language (SQL), both of which are incompatible.

The ORM layer maps a class to a table in a relational database, with its attributes matching the table's field structure.

Object Relational Mapping or ORM is the ability to create a SQL query using object-oriented programming language such as Python.

in simple words , django uses ORM to interact and perform operations on the database

let's understand the ways to interact and performing operations using ORM
in Django,

# models.py
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)


    def __str__(self):
        return self.name

class Book(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
    title = models.CharField(max_length=200)

    def __str__(self):
        return self.title

Now, in the code above, we create two tables in a database named Author and Book in the demoapp.

(djenv) C:\djenv\demoproject>python manage.py shell

  1.    #create a object of the Author class1) save() method of models.Model calss creates a row in the author table
       >>> from demoapp.models import Author
       >>> a = Author(name='vaibhav')
       >>> a.save()
    

    2)The Author.objects gives the Manager of the model. It handles all the CRUD operations on the database table. For example, an object can also be created with the create() method as follows:

     >>Author.objects.create(name='sarthak')
    

    The create() method actually performs the INSERT operation of SQL.

Now, let us add two objects to the Book model. Note that one of the fields in the Book model refers to an object of the Author table as ForeignKey.

Fetch the Author object with a primary key = 2.

  1.  >>from demoapp.models import Author, Book
    
     >>c = Author.objects.get(pk=2)
     >>print(c.name)
    
1
Subscribe to my newsletter

Read articles from Vaibhav Jadhav directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vaibhav Jadhav
Vaibhav Jadhav