Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 1 of 10 · Django Models & ORM
Interview question

What is Django's ORM and what problem does it solve? Django का ORM क्या है और यह कौन-सी problem solve करता है?

Answer

Django's ORM (Object-Relational Mapper) lets developers interact with the database using Python classes and methods instead of writing raw SQL, mapping Python objects to database tables automatically.

# models.py - defining a model maps directly to a database table
from django.db import models

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

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    published_date = models.DateField()
    price = models.DecimalField(max_digits=6, decimal_places=2)

# Using the ORM - no raw SQL needed
book = Book.objects.create(
    title='Django for Beginners',
    author=Author.objects.create(name='John', email='john@example.com'),
    published_date='2024-01-01',
    price=29.99
)

# Equivalent raw SQL the ORM generates behind the scenes (roughly):
# INSERT INTO myapp_book (title, author_id, published_date, price)
# VALUES ('Django for Beginners', 1, '2024-01-01', 29.99);

books = Book.objects.filter(price__lt=50)
for b in books:
    print(b.title, b.author.name)
BenefitExplanation
Database portabilitySame Python code works across PostgreSQL, MySQL, SQLite, etc.
SQL injection protectionORM automatically parameterizes queries
MigrationsSchema changes tracked and versioned as Python code

Django का ORM (Object-Relational Mapper) developers को raw SQL लिखने की बजाय Python classes और methods से database से interact करने देता है, Python objects को automatically database tables से map करता है।

# models.py
from django.db import models

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

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    published_date = models.DateField()
    price = models.DecimalField(max_digits=6, decimal_places=2)

# ORM use करना - raw SQL नहीं चाहिए
book = Book.objects.create(
    title='Django for Beginners',
    author=Author.objects.create(name='John', email='john@example.com'),
    published_date='2024-01-01',
    price=29.99
)

books = Book.objects.filter(price__lt=50)
for b in books:
    print(b.title, b.author.name)
फायदाविवरण
Database portabilityPostgreSQL, MySQL, SQLite में same code चलता है
SQL injection protectionORM automatically queries parameterize करता है
MigrationsSchema changes tracked और versioned

Was this answer clear?