Introduction
In Django, Models are the single, definitive source of truth about your data. They define the structure of your database by mapping Python classes to database tables. Django models are part of the Model-View-Template (MVT) architecture, playing the "Model" role.
What is a Django Model?
A Django model is a Python class that inherits from django.db.models.Model. Each attribute in the class represents a field in the database table.
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)
This will generate a table in the database with columns: id, title, author, published_date, and isbn.
Meta Class – Model Configuration
The Meta class allows you to configure behavior of your model:
class Book(models.Model): title = models.CharField(max_length=200) class Meta: ordering = ['title'] # Default ordering verbose_name = "Book" verbose_name_plural = "Books" db_table = 'library_books' # Custom table name
Model Methods
You can define custom methods inside models to add behavior:
class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=100) def __str__(self): return f"{self.title} by {self.author}" def get_author_uppercase(self): return self.author.upper()
Example of my model data
CRUD Operations with Models
1.Create – Adding a New Record
2.Read – Retrieving Records
3.Update – Changing Existing Data
4.Delete – Removing a Record
** Model Validation**
Use clean() or full_clean() to enforce custom validations.
def clean(self): if self.published_date > timezone.now().date(): raise ValidationError("Publish date cannot be in the future.")
Advanced Model Features
Custom Managers
it is created by definining a custom manager by subclassing models.Manager.
Model Inheritance
A powerful feature that allows you to reuse common fields or logic across multiple models.
Final Thoughts
Django Models are the backbone of any Django project. They offer a rich, declarative, and powerful way to define, query, and manage your database schema all in clean Python code. Understanding how models work is essential for any Django developer building robust, scalable web applications.
Top comments (0)