How to Use Django Models for Database Management

๐Ÿ› ️ How to Use Django Models for Database Management

Django models are Python classes that define the structure of your database tables. They allow you to manage your database using Python code, without writing raw SQL.


✅ Step 1: Set Up a Django Project (If You Haven’t Already)

bash

Copy

Edit

django-admin startproject myproject

cd myproject

python manage.py startapp myapp

Add 'myapp' to your INSTALLED_APPS in settings.py.

๐Ÿงฉ Step 2: Create a Model

Inside myapp/models.py, define your data structure using Python classes:


python

Copy

Edit

from django.db import models


class Book(models.Model):

    title = models.CharField(max_length=200)

    author = models.CharField(max_length=100)

    published_date = models.DateField()

    isbn = models.CharField(max_length=13)

    price = models.DecimalField(max_digits=6, decimal_places=2)


    def __str__(self):

        return self.title

Each class becomes a database table, and each attribute becomes a column.


⚙️ Step 3: Apply the Model to the Database

Run the following commands to create database tables from your models:


bash

Copy

Edit

python manage.py makemigrations

python manage.py migrate

makemigrations: Prepares the migration files.


migrate: Applies those changes to your actual database.


✏️ Step 4: Add, Retrieve, Update, and Delete Data

➕ Add a Record

python

Copy

Edit

from myapp.models import Book

book = Book(title="Django for Beginners", author="John Doe", published_date="2024-01-01", isbn="1234567890123", price=29.99)

book.save()

๐Ÿ“ฅ Retrieve Records

python

Copy

Edit

Book.objects.all()                     # Get all books

Book.objects.get(id=1)                # Get book by ID

Book.objects.filter(author="John Doe")  # Get books by author

๐Ÿ” Update a Record

python

Copy

Edit

book = Book.objects.get(id=1)

book.price = 24.99

book.save()

❌ Delete a Record

python

Copy

Edit

book = Book.objects.get(id=1)

book.delete()

๐Ÿงช Step 5: Use the Django Admin

You can manage data visually by registering your model in admin.py:


python

Copy

Edit

from django.contrib import admin

from .models import Book


admin.site.register(Book)

Then create a superuser:


bash

Copy

Edit

python manage.py createsuperuser

Log in at http://localhost:8000/admin and manage your database records through the UI.


๐Ÿ“˜ Common Field Types

Field Type Description

CharField Short text (requires max_length)

TextField Long text

IntegerField Integer

BooleanField True/False

DateField Date only

DateTimeField Date and time

DecimalField Decimal numbers

ForeignKey Many-to-one relationship


๐Ÿง  Tips & Best Practices

Use __str__ to return a readable name in admin and shell.


Use Meta class to define ordering or table name.


Keep models clean — use managers or services for business logic.


๐Ÿ”š Summary

Task Command or Code

Define Model models.Model subclass

Create Migration python manage.py makemigrations

Apply Migration python manage.py migrate

Manage Data Book.objects.create(), etc.

Use Admin Register model in admin.py

Learn Full Stack Python Course in Hyderabad

Read More

Introduction to Object-Relational Mapping (ORM) in Python

Python Database Management: PostgreSQL vs MySQL

Visit Our Quality Thought Training in Hyderabad

Get Directions


Comments

Popular posts from this blog

Understanding Snowflake Editions: Standard, Enterprise, Business Critical

Why Data Science Course?

How To Do Medical Coding Course?