Django ORM

engrmahabub
Mahabubur Rahman
Published on Jan, 14 2024 1 min read 0 comments
image

A broad Guide to Database Interactions in Django.


Django ORM, authorized developers to interact with databases using Python classes and methods. It abstracts away the intricacies of SQL queries, permit for seamless and intuitive database operations. By defining models as Python classes, developers can easily create, retrieve, update, and delete records.

 

What is ORM?

ORM standard for Object Relational Mapping. It is the technique that allow you to interact with database server using high level language code, instead of writing SQL queries. Django ORM provides you to define database schema and performing database operation using Python classes and methods.

Lets create a simple Django Model - 

 

from django.db import models

from django.contrib.auth.models import User



class Student(models.Model):
    full_name = models.CharField(max_length=50)
    address = models.TextField()
    email = models.EmailField()
  • Apply - makemigrations to create migration file.
  • Apply - migrate to the model in database as database table.

Let's do CRUD operation for the above model in simple way - 

Create - 

from .models import Student
student = Student(full_name='Mosiur Rahman',address='Road#3,Gulshan 1,Dhaka,Bangladesh',email='[email protected]')
student.save()

Read - 

from .models import Student
all_student = Student.objects.all()

Update - 

from .models import Student
student = Student.objects.get(id=1)
student.full_name = 'Mosiur Rahmani'
student.save() 

Delete - 

from .models import Student
student = Student.objects.get(id=1)
student.delete()

 

Why use Django ORM?

Django ORM provides strong and suitable way to interact with databases, abstracting way much of the difficulty  involved in working face to face with database.

 

 

 

 

 

0 Comments