In Django’s MVT architecture, the Model is responsible for handling everything related to the database. It defines how data is structured, stored, and accessed.
What Is a Model?
A Model is a Python class that inherits from django.db.models.Model
. Each model maps to a database table, and each attribute in the class represents a column in that table.
Defining a Simple Model
python
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.CharField(max_length=100)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
CharField– for short text like titles or names
TextField– for longer content
DateTimeField– stores the timestamp when the object is created
Making Migrations
After defining the model:
python manage.py makemigrations
python manage.py migrate
Performing CRUD operations
Create .
python
Post.objects.create(
title="Hello", content="My first post", author="admin"
)
Read
python
Post.objects.all()
Post.objects.get(id=1)
Post.objects.filter(author="admin")
Update
python
post = Post.objects.get(id=1)
post.title = "Updated Title"
post.save()
Delete
python
post = Post.objects.get(id=1)
post.delete()
Model Relationships.
To create relationships between tables, Django provides:
python
class Category(models.Model):
name = models.CharField(max_length=100)
class Post(models.Model):
title = models.CharField(max_length=200)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
This sets up a one-to-many relationship where each post belongs to one category.
Registering Models in Admin.
To display your model in the admin panel:
python
from django.contrib import admin
from .models import Post
admin.site.register(Post)
Now the model appears in the admin dashboard at
Conclusion.
Django Models make it simple to define, structure, and work with your database using just Python code. Whether you're building a blog, an inventory system, or a social network, models are the core of your data layer. Once you understand how to create and interact with them, you unlock one of Django’s most powerful features.
Top comments (0)