How to Use Django Models for Database Management
How to Use Django Models for Database Management
Using Django Models is one of the most efficient ways to manage your database in Django. Models define the structure of your database tables and let you interact with the data using Python code instead of SQL.
π§ What Is a Django Model?
A Django model is a Python class that maps to a single table in a database. Each model class defines fields (columns) and behaviors of the data you’re storing.
π§± Step-by-Step: Using Django Models for Database Management
1. Define a Model
In your Django app (e.g., blog), open or create models.py.
python
Copy
Edit
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
published_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
2. Create Database Tables
After defining models, generate and apply database migrations.
bash
Copy
Edit
# Generate migration file
python manage.py makemigrations
# Apply migrations to update the database schema
python manage.py migrate
3. Use the Model (Python Shell or Views)
In the Django shell:
bash
Copy
Edit
python manage.py shell
python
Copy
Edit
from blog.models import Post
# Create a new post
post = Post(title="First Post", content="This is my first blog post.")
post.save()
# Query all posts
Post.objects.all()
# Get a specific post
Post.objects.get(id=1)
# Filter posts
Post.objects.filter(title__icontains="First")
π ️ Common Field Types in Django Models
Field Type Description
CharField Short text (requires max_length)
TextField Long text
IntegerField Integer number
DateTimeField Date and time
BooleanField True/False
ForeignKey Many-to-one relationship
ManyToManyField Many-to-many relationship
π Model Relationships Example
python
Copy
Edit
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
π§ͺ Using Models in Admin Panel
Register your models in admin.py:
python
Copy
Edit
from django.contrib import admin
from .models import Post
admin.site.register(Post)
Then run the server and go to http://127.0.0.1:8000/admin to manage your data via a GUI.
✅ Summary
Task How to Do It
Define database tables Create model classes in models.py
Apply changes makemigrations → migrate
Add/edit data Use model methods or Django Admin
Query data Use the Django ORM (e.g., .filter())
Would you like a full example project or API integration using Django models?
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 IHUB Talent Training Institute in Hyderabad
Comments
Post a Comment