Chapter 11: Django Models

perfect timing to talk about Django Models, which are truly the backbone of any real Django application.

You’ve already got:

  • Virtual env + Django 6.0.1 installed
  • Project (mysite)
  • App (polls)
  • Views, URLs, templates basics

Now models let you define your data structure — like “What is a Question? What is a Choice?” — and Django automatically handles creating database tables, relationships, queries, validation, and even the admin interface for free.

Think of models as smart Python classes that represent database rows/tables. One model class = one database table (usually). Django’s ORM (Object-Relational Mapper) lets you work with database data using pure Python — no raw SQL needed for 90% of cases.

We’ll build the classic polls models step-by-step (exactly like the official tutorial but explained more conversationally, with extra tips, common mistakes, and 2026 notes).

Step 1: Where Do Models Live?

In your app folder:

text

Open polls/models.py (it’s almost empty by default — perfect).

Step 2: Import What We Need

At the top:

Python

Step 3: Define the Two Main Models – Question & Choice

We’ll create:

  • Question: A poll question (e.g. “What’s your favorite color?”)
  • Choice: An option for that question (e.g. “Red”, “Blue”) with vote count
Python

Key concepts explained like a teacher:

  • Every model inherits from models.Model → gives ORM magic
  • Fields = class attributes (like question_text = models.CharField(…))
  • Common field types:
    • CharField → short text (always need max_length)
    • DateTimeField → date + time
    • IntegerField → numbers
    • ForeignKey → many-to-one relationship (many choices → one question)
  • on_delete=models.CASCADE → “if parent gone, children gone” (most common)
  • __str__() → what shows in admin, shell, debug (never leave default!)
  • class Meta → model options (ordering, names, permissions…)
  • verbose_name → human-friendly names in admin/forms
  • Custom method (was_published_recently) → call in templates: {{ question.was_published_recently }}

Step 4: Make & Apply Migrations (Create Tables!)

Django doesn’t touch the database until you tell it to.

  1. Detect changes & create migration files (like git commits for DB)

    Bash

    Output something like:

    text

    These files are Python code — safe to commit to git!

  2. Apply migrations (actually run SQL to create tables)

    Bash
    • First time → also creates Django’s built-in tables (auth, sessions, admin…)
    • Output: “Applying polls.0001_initial… OK”

Now your SQLite database (db.sqlite3) has real tables!

Step 5: Play with Models in the Shell (Super Useful for Learning!)

Bash

Inside Python shell:

Python

Exit with exit()

Step 6: Register Models in Admin (Instant CRUD UI!)

Open polls/admin.py:

Python

Better version (recommended – makes admin much nicer):

Python

Run server → http://127.0.0.1:8000/admin/ Login (create superuser if not done: python manage.py createsuperuser) → You can now add/edit questions & choices via beautiful UI!

Common Beginner Mistakes & Fixes

  • No changes detected in makemigrations → forgot to save models.py or typo
  • OperationalError: no such table → forgot migrate after makemigrations
  • FieldError → wrong field name or missing max_length on CharField
  • RelatedObjectDoesNotExist → trying q.choices before saving q
  • Migrations conflict → deleted old migration files manually → use –fake carefully or reset DB

Quick Recap Table – Core Model Ideas

Concept Example in Code Why Important
Model class class Question(models.Model): Defines table structure
Field question_text = models.CharField(…) Columns in DB
ForeignKey question = models.ForeignKey(Question, …) Relationships (many-to-one)
__str__() return self.question_text Human-readable representation
Custom method def was_published_recently(self): Business logic, usable in templates/admin
Meta class ordering = [“-pub_date”] Default sort, names, permissions
ORM Manager Question.objects.all() Query interface (filter, get, create…)

What’s Next? Your Call!

You’ve now:

  • Defined models
  • Created & applied migrations
  • Played in shell
  • Got admin working

Tell me:

  • “Let’s add more fields / relationships (ManyToMany, OneToOne)”
  • “How to query models in views (filter, order_by, count…)”
  • “Explain migrations deeper (squash, fake, rollback)”
  • “Show me how to use models in templates (with for loops)”
  • Or “I got this error after migrate — help!” (paste it)

You’re building a full app now — models are the foundation, and yours is solid! 💪🚀 Let’s keep going!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *