ORM helps you work with databases using Python code instead of writing SQL. It makes saving and getting data easier and safer.
When you want to save user information from a web form into a database.
When you need to get a list of products from the database to show on a website.
When you want to update or delete records without writing SQL queries.
When you want to keep your database code organized and easy to read.
When you want to avoid mistakes from writing raw SQL by hand.
Syntax
Django
class ModelName(models.Model):
field_name = models.FieldType(options)
# Example:class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
Each model class represents a database table.
Each field in the model represents a column in the table.
Examples
This model creates a table with columns for name and age.
Django
class Person(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
This model stores product names and prices with decimals.
Django
class Product(models.Model):
name = models.CharField(max_length=50)
price = models.DecimalField(max_digits=6, decimal_places=2)
Sample Program
This example shows how to define a Car model, save a new car to the database, and then get and print all car brands using ORM.
Django
from django.db import models
class Car(models.Model):
brand = models.CharField(max_length=50)
year = models.IntegerField()
# Using the ORM in a Django shell or view:# Create a new car
car = Car(brand='Toyota', year=2020)
car.save()
# Get all cars
all_cars = Car.objects.all()
# Print car brandsfor c in all_cars:
print(c.brand)
OutputSuccess
Important Notes
ORM hides SQL details so you can focus on Python code.
It helps prevent SQL injection security problems.
Remember to run migrations to create database tables from models.
Summary
ORM lets you use Python classes to work with database tables.
It simplifies saving, retrieving, and updating data.
Using ORM makes your code cleaner and safer.
Practice
(1/5)
1. Why does Django use an ORM to map Python classes to database tables?
easy
A. To prevent any changes to the database structure
B. To make the database run faster by skipping Python
C. To force developers to write raw SQL queries
D. To let developers work with databases using Python code instead of SQL
Solution
Step 1: Understand ORM purpose
ORM stands for Object-Relational Mapping, which connects Python objects to database tables.
Step 2: Identify why mapping is useful
This allows developers to use Python code to create, read, update, and delete data without writing SQL.
Final Answer:
To let developers work with databases using Python code instead of SQL -> Option D
Quick Check:
ORM = Python code for database [OK]
Hint: ORM means use Python classes, not SQL, for database [OK]
Common Mistakes:
Thinking ORM makes database faster by skipping Python
Believing ORM forces raw SQL writing
Assuming ORM blocks database changes
2. Which of the following is the correct way to define a Django model field that maps to a database column?
easy
A. name = models.FieldChar(100)
B. name = CharField(max_length=100)
C. name = models.CharField(max_length=100)
D. name = models.Char(100)
Solution
Step 1: Recall Django model field syntax
Django model fields are defined using models.FieldType() with parameters.
Step 2: Match correct field type and parameters
CharField is the correct field for text with a max length, and it requires max_length.
Final Answer:
name = models.CharField(max_length=100) -> Option C
Quick Check:
Correct field syntax = name = models.CharField(max_length=100) [OK]
Hint: Use models.FieldType() with parameters for fields [OK]
Common Mistakes:
Omitting 'models.' prefix
Using wrong field class names
Passing parameters incorrectly
3. Given this Django model and code:
class Book(models.Model):
title = models.CharField(max_length=50)
book = Book(title='Django Guide')
book.save()
print(Book.objects.count())
What will be printed?
medium
A. 0
B. 1
C. Error because save() is missing arguments
D. The title 'Django Guide'
Solution
Step 1: Understand model instance creation and saving
Creating book with title and calling save() stores it in the database.
Step 2: Check what Book.objects.count() does
This counts how many Book records exist in the database, which is 1 after saving.
Final Answer:
1 -> Option B
Quick Check:
Saved one book, count = 1 [OK]
Hint: save() adds record, count() shows total saved [OK]
Common Mistakes:
Thinking save() needs arguments
Confusing count() with printing title
Assuming count() returns 0 before save
4. What is wrong with this Django model code?
class Author(models.Model):
name = models.CharField(max_length=50)
author = Author(name='Alice')
author.save(name='Bob')
medium
A. save() method does not accept arguments like name
B. CharField requires max_length to be 100 or more
C. Model class must be named with lowercase
D. You cannot create model instances with parameters
Solution
Step 1: Check save() method usage
The save() method does not take field values as arguments; it saves current instance data.
Step 2: Identify correct way to update fields
To change a field, assign it before calling save(), e.g., author.name = 'Bob'.
Final Answer:
save() method does not accept arguments like name -> Option A
Quick Check:
save() takes no args, just saves instance [OK]
Hint: save() saves instance, does not take field args [OK]
Common Mistakes:
Passing fields to save() method
Thinking max_length must be >=100
Naming model classes lowercase
5. You want to update all books with title 'Old Title' to 'New Title' using Django ORM. Which code correctly does this efficiently?