DEV Community

Cover image for DJANGO MODELS
yvonne20865
yvonne20865

Posted on

DJANGO MODELS

If you're diving into Django, there's no escaping Django Models they're the backbone of any Django powered app. Whether you're building a blog, an e-commerce site, or the next social media giant, you'll be working with models all the way. This post is your comprehensive, human-friendly guide to Django Models, packed with code examples and real-world tips.
A Django Model is a Python class that represents a database table. It defines the fields and behaviors of the data you want to store.Let's get into it.

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    birth_date = models.DateField(null=True, blank=True)

    def __str__(self):
        return self.name
Enter fullscreen mode Exit fullscreen mode

Basic Fields
Django gives you a variety of fields to work with:

class Book(models.Model):
    title = models.CharField(max_length=200)
    pages = modelcs.IntegerField()
    price = models.DecimalField(max_digits=5, decimal_places=2)
    release_date = models.DateField()
    in_stock = models.BooleanField(default=True)
Enter fullscreen mode Exit fullscreen mode

Relationships: ForeignKey, ManyToMany, One To One
ForeignKey (Many-to-One)

class Book(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

Enter fullscreen mode Exit fullscreen mode

ManyToManyField

class Genre(models.Model):
    name = models.CharField(max_length=50)

class Book(models.Model):
    genres = models.ManyToManyField(Genre)
Enter fullscreen mode Exit fullscreen mode

OneToOneField

class Profile(models.Model):
    user = models.OneToOneField('auth.User', on_delete=models.CASCADE)
    bio = models.TextField()
Enter fullscreen mode Exit fullscreen mode

Meta Options
You can control behavior like ordering, table names, and verbose names using the Meta class:

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

    class Meta:
        db_table = 'book_publishers'
        ordering = ['name']
        verbose_name = 'Publisher'
        verbose_name_plural = 'Publishers'
Enter fullscreen mode Exit fullscreen mode

Field Options

class Article(models.Model):
    title = models.CharField(
        max_length=200,
        null=True,        # Can be NULL in database
        blank=True,       # Can be empty in forms
        unique=True       # Must be unique
    )
Enter fullscreen mode Exit fullscreen mode

Choices for Fields

class Book(models.Model):
    FORMAT_CHOICES = [
        ('H', 'Hardcover'),
        ('P', 'Paperback'),
        ('E', 'Ebook')
    ]
    format = models.CharField(max_length=1, choices=FORMAT_CHOICES)
Enter fullscreen mode Exit fullscreen mode

Auto Fields

class Audit(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

Enter fullscreen mode Exit fullscreen mode

Custom Methods

class Book(models.Model):
    title = models.CharField(max_length=100)
    release_date = models.DateField()

    def is_new_release(self):
        from datetime import date, timedelta)
        return self.release_date >= date.today() - timedelta(days=30
Enter fullscreen mode Exit fullscreen mode

get_absolute_url

from django.urls import reverse

class Book(models.Model):
    def get_absolute_url(self):
        return reverse('book_detail', args=[str(self.id)])
Enter fullscreen mode Exit fullscreen mode

Custom Managers

class BookManager(models.Manager):
    def published(self):
        return self.filter(release_date__isnull=False)

class Book(models.Model):
    title = models.CharField(max_length=100)
    release_date = models.DateField(null=True)

    objects = BookManager()

# Usage
Book.objects.published()
Enter fullscreen mode Exit fullscreen mode

Model Inheritance

class TimestampedModel(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

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

Multi-table Inheritance

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

class Dog(Animal):
    breed = models.CharField(max_length=50)
Enter fullscreen mode Exit fullscreen mode

Model Signals

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Author)
def author_saved(sender, instance, **kwargs):
    print(f"Author saved: {instance.name}")

Enter fullscreen mode Exit fullscreen mode

Migrations

python manage.py makemigrations
python manage.py migrate

Enter fullscreen mode Exit fullscreen mode

Querying the Database

# All books
Book.objects.all()

# Filter
Book.objects.filter(title__icontains="django")

# Get one object
Book.objects.get(id=1)

# Create
Book.objects.create(title="New Book", release_date="2025-07-01")

# Update
book = Book.objects.get(id=1)
book.title = "Updated Title"
book.save()

# Delete
book.delete()

Enter fullscreen mode Exit fullscreen mode

Final Thoughts
Django Models are deep, flexible, and incredibly powerful. The best way to master them is to build real projects and tweak your models as you go. This guide gives you a solid foundation but don’t stop here. Play, break things, and learn by doing!
Got questions or want a deep-dive on model relationships drop a comment down below.

Top comments (0)