DEV Community

zipporahmutanu04
zipporahmutanu04

Posted on

Day 6: Django Models Made Simple: A Beginner’s Guide With Code Examples

🎓 What is a Django Model?

When you build a web application, you almost always need to store data — like users, posts, products, comments, etc.
This data is stored in a database (e.g., SQLite, PostgreSQL, MySQL).

Instead of writing SQL queries by hand, Django lets you use models, which are simple Python classes.

📌 A Django model is just a Python class that describes what your data looks like.
📌 Django then takes that class and creates the actual database table for you.

📄 How do you write a model?
You write models in the models.py file of your Django app.

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    published_at = models.DateTimeField(auto_now_add=True)
Enter fullscreen mode Exit fullscreen mode

What does this do?
✅ Django will create a table named post.
✅ The table will have 3 columns:

title — a short text (maximum 200 characters)

body — long text

published_at — date and time when the post was created

🔨 How does Django turn models into a database table?
After you define the model:
1️⃣ Run:

python manage.py makemigrations
This tells Django to create a migration file (a plan for creating the table).

2️⃣ Run:

python manage.py migrate
This actually creates the table in the database.

🧪 Examples of Fields You Can Use
Here are some common field types:

name = models.CharField(max_length=100)  # short text
description = models.TextField()         # long text
Enter fullscreen mode Exit fullscreen mode

Numbers

price = models.DecimalField(max_digits=6, decimal_places=2)
quantity = models.IntegerField()
Enter fullscreen mode Exit fullscreen mode

Dates & Times

created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
Enter fullscreen mode Exit fullscreen mode

Boolean (True/False)

is_published = models.BooleanField(default=False)
Enter fullscreen mode Exit fullscreen mode

Email & Slug

email = models.EmailField()
slug = models.SlugField()
Enter fullscreen mode Exit fullscreen mode

🔗 How to Link Tables Together?
One-to-Many (ForeignKey)
Example: Many books → One author

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
Enter fullscreen mode Exit fullscreen mode

Many-to-Many
Example: Students and Courses

class Student(models.Model):
    name = models.CharField(max_length=100)

class Course(models.Model):
    name = models.CharField(max_length=100)
    students = models.ManyToManyField(Student)
Enter fullscreen mode Exit fullscreen mode

🧂 Options You Can Add
Make a field required or optional:

name = models.CharField(max_length=100, blank=True, null=True)
Choices
Enter fullscreen mode Exit fullscreen mode

Let users choose only from a set of values:

STATUS_CHOICES = [
    ('draft', 'Draft'),
    ('published', 'Published'),
]

status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
Enter fullscreen mode Exit fullscreen mode

Unique
Make sure no duplicates:

email = models.EmailField(unique=True)
Enter fullscreen mode Exit fullscreen mode

🏗️ CRUD: How to Use the Model in Code?
Once your model and table are ready, you can use Django’s ORM (Object Relational Mapper) to interact with your data.

post = Post.objects.create(title="Hello", body="This is my first post!")
Enter fullscreen mode Exit fullscreen mode

Read

all_posts = Post.objects.all()
one_post = Post.objects.get(id=1)
Enter fullscreen mode Exit fullscreen mode

Update

post = Post.objects.get(id=1)
post.title = "Updated Title"
post.save()
Enter fullscreen mode Exit fullscreen mode

Delete

post = Post.objects.get(id=1)
post.delete()
Enter fullscreen mode Exit fullscreen mode

📐 More Advanced Examples
Automatically generate a slug

from django.utils.text import slugify

class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(blank=True)

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super().save(*args, **kwargs)
Enter fullscreen mode Exit fullscreen mode

Abstract Base Class
You can create reusable base models:

class TimeStampedModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class Post(TimeStampedModel):
    title = models.CharField(max_length=100)
Enter fullscreen mode Exit fullscreen mode

Custom QuerySet Manager

class PublishedManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(is_published=True)

class Article(models.Model):
    title = models.CharField(max_length=100)
    is_published = models.BooleanField(default=False)
Enter fullscreen mode Exit fullscreen mode
objects = models.Manager()  # Default manager
published = PublishedManager()  # Custom manager
Enter fullscreen mode Exit fullscreen mode

🤔 Why Use Django Models?
✅ They save you from writing SQL by hand.
✅ Keep all your data structure in one place.
✅ Automatically create and manage tables.
✅ Allow you to write Python instead of SQL.

🚀 Summary:
What you define What happens
Python class Table
Attributes Columns
Create .create()
Read .all(), .filter()
Update .save()
Delete .delete()

Top comments (0)