MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Creating Models0%
Study Materials
Django for Backend DevelopmentProgress 0%
1.1Installing Django & Environment Setup1.2Django Project Structure1.3Creating First Django App
2.1Creating Models2.2Field Types & Relationships2.3Migrations & ORM Queries
HomeTutorialsDjango for Backend DevelopmentCreating Models
Field Types & Relationships

Creating Models

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Django's Object-Relational Mapper (ORM) allows you to define your database schema using clean, idiomatic Python classes. A Django model is the single, definitive source of truth about your data: it contains the essential fields and behaviors of the data you're storing. Django automatically maps model classes to SQL database tables and handles migrations without writing raw SQL.


1. Defining a Model Class

Every model inherits from django.db.models.Model. Each class attribute represents a database column.

1# articles/models.py
2from django.db import models
3from django.utils.text import slugify
4 
5class Article(models.Model):
6 # Core data fields
7 title = models.CharField(max_length=200, help_text="Article headline")
8 slug = models.SlugField(max_length=200, unique=True, db_index=True)
9 content = models.TextField()
10
11 # Status choices
12 STATUS_CHOICES = [
13 ("draft", "Draft"),
14 ("published", "Published"),
15 ("archived", "Archived"),
16 ]
17 status = models.CharField(max_length=20, choices=STATUS_CHOICES, default="draft")
18
19 # Numerical and Boolean fields
20 view_count = models.PositiveIntegerField(default=0)
21 is_featured = models.BooleanField(default=False)
22
23 # Automatic audit timestamps
24 created_at = models.DateTimeField(auto_now_add=True) # Set only upon creation
25 updated_at = models.DateTimeField(auto_now=True) # Updated on every save()
26 
27 class Meta:
28 # Table metadata configuration
29 db_table = "enterprise_articles"
30 ordering = ["-created_at"] # Default ordering: newest first
31 verbose_name = "Article"
32 verbose_name_plural = "Articles"
33 
34 def __str__(self):
35 return f"{self.title} ({self.status})"
36 
37 def save(self, *args, **kwargs):
38 # Automatically generate URL slug if empty
39 if not self.slug:
40 self.slug = slugify(self.title)
41 super().save(*args, **kwargs)

2. Model Field Options

Django field definitions accept universal configuration options:

  • null=True: Allows the database column to store NULL values. (Avoid on CharField/TextField where Django conventions prefer empty strings "").
  • blank=True: Controls form/admin validation; allows the field to be submitted empty in web forms.
  • default=value: Default value assigned when creating a new record.
  • unique=True: Enforces an SQL UNIQUE constraint on the column.
  • db_index=True: Creates an SQL B-tree index on the column for accelerated lookup speeds.

3. The auto_now vs auto_now_add Timestamp Rule

  • auto_now_add=True: Automatically sets the field to now() when the object is first created. Ideal for created_at.
  • auto_now=True: Automatically updates the field to now() every time the record is saved via save(). Ideal for updated_at.

4. Generating and Applying SQL Migrations

Whenever you create or modify a model:

1# 1. Inspect models and generate migration scripts in articles/migrations/
2python manage.py makemigrations articles
3 
4# 2. View raw SQL that Django will execute (optional inspection)
5python manage.py sqlmigrate articles 0001
6 
7# 3. Apply changes to physical database tables
8python manage.py migrate

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What class must all Django models inherit from?
Question 2
What is the difference between null=True and blank=True in Django model fields?
Question 3
How does auto_now_add=True differ from auto_now=True on DateTimeField?
Question 4
Why is defining a __str__ method on models considered an enterprise best practice?
Question 5
What command generates Python migration files from modified models without applying them to the database?
Next Lesson

Field Types & Relationships

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Creating First Django AppField Types & Relationships

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Django for Backend Development with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext