Models and ORM in Django

A Django model is a class that represents a table in your database. It is the single, definitive source of information about your data. It contains the essential attributes and behaviors of the data you’re storing. Generally, each model maps to a single database table.

Object-Relational Mapping (ORM) is a technique that lets you query and manipulate data from a database using an object-oriented paradigm. It significantly speeds up development and the developer doesn't necessarily need to know the exact queries for the underlying database.

Getting Started

This blog demonstrates the use of Models and ORM in Django for Postgres database. Let's get started by creating a database using a simple python script.
We'll use psycopg2 library for creating connection, cursor, and running a raw SQL query. Install it using pip install psycopg2

create_database.py

import psycopg2
  
# connection establishment
conn = psycopg2.connect(
   database="postgres",
    user='postgres',
    password='root',
    host='localhost',
    port= '5432'
)
  
conn.autocommit = True
  
# Creating a cursor object
cursor = conn.cursor()
  
# query to create a database
db_name = 'main_db'
sql = f''' CREATE database {db_name}''';
  
# executing above query
cursor.execute(sql)
print(f"Database {db_name} has been created successfully!!");
  
# Closing the connection
conn.close()

Output

Database main_db has been created successfully!!

After creating the database, we can start writing models and orm queries in django.

Note: Before proceeding further, make sure to list your application under INSTALLED_APPS in settings.py file. Also, Make sure to configure your database engine and parameters in settings.py.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'main_db',
        'USER': 'postgres',
        'PASSWORD': 'root',
        'HOST': 'localhost'
    }
}

app/model.py

from django.db import models

class Vehicles(models.Model):
    id = models.BigAutoField(primary_key=True)
    vehicle_no = models.BigIntegerField(unique=True)
    name = models.CharField(max_length=30)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    type = models.SmallIntegerField()
    
    # Insert entry into table
    @classmethod
    def insert(cls, params):
        obj = cls.objects.create(
            vehicle_no= params.get('vehicle_no'),
            name = params.get('name'),
            price = params.get('price'),
            type = params.get('type'),
            color = params.get('color')
            )
            
    # Get data from table
    @classmethod
    def fetch_by_ids(cls, ids):
        db_rows = cls.objects.filter(id__in=ids)
        response = {}
        for db_row in db_rows:
            format_db_row = cls.format_db_data(db_row)
            response[format_db_row["id"]] = format_db_row

        return response

    
    # Update price of a vehicle
    @classmethod
    def update(cls, id, new_price):
        obj = cls.objects.filter(id=id).update(price=new_price)

We'll have to run the following two commands to create a table Vehicle in database main_db:

  1. python manage.py makemigrations - which is responsible for creating new migrations based on the changes you have made to your models.
  2. python manage.py migrate - which is responsible for applying and unapplying migrations

Now, Once the migrations are successful, We can use the listed functions insert,fetch_by_ids and update to insert, get and update entries in our table respectively.

Ending Note: It's highly encouraged to use django models, orm and migration for elementary use cases as it significantly reduces development efforts, makes it maintainable and speeds up the development.

Kartik Kapgate

Kartik Kapgate

Software Engineer | Backend