0
0
Djangoframework~5 mins

Why ORM maps Python to database in Django

Choose your learning style9 modes available
Introduction

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 brands
for 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.