Django Models are Python classes that define the structure of your database tables. Each of the model represents a sql table, and each attribute in the model represents a database field. Django’s ORM (Object-Relational Mapper) allows you to interact with the database using Python code instead of writing SQL queries.
Why Use Django Models?
- Create database tables using Python classes
- Perform CRUD operations easily
- Manage relationships between tables
- Automatically generate database schemas
- Work with databases without writing SQL
Creating a Model
Open the models.py file and define your model:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Common Model Fields
from django.db import models
class Employee(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
age = models.IntegerField()
salary = models.DecimalField(max_digits=10, decimal_places=2)
is_active = models.BooleanField(default=True)
joined_date = models.DateField()
Frequently Used Fields
| Field Type | Description |
|---|---|
| CharField | Stores short text |
| TextField | Stores large text |
| IntegerField | Stores integers |
| FloatField | Stores decimal numbers |
| DecimalField | Stores precise decimal values |
| BooleanField | Stores True/False values |
| DateField | Stores dates |
| DateTimeField | Stores date and time |
| EmailField | Stores email addresses |
| ImageField | Stores image files |
| FileField | Stores uploaded files |
Register the App
Add the app to INSTALLED_APPS in settings.py:
INSTALLED_APPS = [
'blog',
]
Create Migrations
Generate migration files:
python manage.py makemigrations
Apply migrations to the database:
python manage.py migrate
Create Records
from blog.models import Post
Post.objects.create(
title="My First Post",
content="Welcome to Django Models"
)
Retrieve Records
posts = Post.objects.all()
for post in posts:
print(post.title)
Update Records
post = Post.objects.get(id=1)
post.title = "Updated Title"
post.save()
Delete Records
post = Post.objects.get(id=1)
post.delete()
Model Relationships
ForeignKey (One-to-Many)
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
)
ManyToManyField
class Tag(models.Model):
name = models.CharField(max_length=50)
class Post(models.Model):
title = models.CharField(max_length=200)
tags = models.ManyToManyField(Tag)
OneToOneField
class UserProfile(models.Model):
user = models.OneToOneField(
User,
on_delete=models.CASCADE
)
bio = models.TextField()
Meta Class
Use the Meta class to customize model behavior:
class Post(models.Model):
title = models.CharField(max_length=200)
class Meta:
ordering = ['-id']
verbose_name = "Post"
verbose_name_plural = "Posts"
Benefits of Django Models
- Database abstraction through ORM
- Easy CRUD operations
- Automatic migrations
- Relationship management
- Database-independent development
- Secure and maintainable code