Introduction to Django Models

Last updated 3 months, 3 weeks ago | 226 views 75     5

Tags:- Python Django

Here’s a detailed and beginner-friendly article introducing Django Models, complete with explanations, examples, and best practices.


Introduction to Django Models

What Are Django Models?

In Django, models are Python classes that define the structure and behavior of the data in your application. Each model maps to a single database table, and each attribute of the model represents a field in that table.

Django models are the heart of Django’s Object-Relational Mapping (ORM) system. They allow developers to interact with the database using Python code instead of writing raw SQL.


Why Use Django Models?

  • Automatic table creation via migrations

  • Validation is built-in

  • Powerful querying using the ORM

  • Scalable and reusable for complex apps

  • Integrated with Django Admin for quick CRUD management


How to Define a Django Model

Every model is a class that inherits from django.db.models.Model.

Example:

# blog/models.py

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    published = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

Field Types Explained:

Field Description
CharField For short strings (must set max_length)
TextField For large text (no length limit)
BooleanField Stores True/False values
DateTimeField Stores date and time
IntegerField Stores integers
SlugField URL-friendly text, useful for slugs
ForeignKey Creates a many-to-one relationship

Using Your Model

After defining your models, you need to apply them to the database.

Step 1: Make Migrations

python manage.py makemigrations

Step 2: Apply Migrations

python manage.py migrate

Step 3: Create and Use Objects in the Shell

python manage.py shell
from blog.models import Post

# Create a post
post = Post(title="My First Post", content="Hello, Django!")
post.save()

# Query all posts
Post.objects.all()

# Filter posts
Post.objects.filter(published=True)

Model Metadata: class Meta

You can add extra behavior or settings using an inner Meta class.

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()

    class Meta:
        ordering = ['-id']  # Default ordering
        verbose_name = "Blog Post"
        verbose_name_plural = "Blog Posts"

The __str__() Method

Always define __str__() to return a readable string version of your object:

def __str__(self):
    return self.title

This is especially useful in the Django Admin and shell.


Full Example: Blog App Models

# blog/models.py

from django.db import models

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

    def __str__(self):
        return self.name

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    published = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

✅ Tips for Django Models

  • Use descriptive field names that match your domain

  • Use auto_now_add=True for creation dates and auto_now=True for update timestamps

  • Always define __str__() for human-readable model output

  • Use Meta class for ordering and naming options

  • Keep your models focused—use multiple models for complex structures


⚠️ Common Pitfalls

Pitfall Solution
Forgetting max_length in CharField Django will raise an error
Editing models but not migrating Always run makemigrations and migrate
Missing __str__() method Objects will appear as <Post object> instead of readable text
Forgetting to register models in admin Won’t appear in Django Admin until registered
Misusing ForeignKey Always define on_delete=models.CASCADE or another strategy

Conclusion

Django models provide a clean and powerful way to manage your data. With models, you get a full-featured database abstraction that scales from small projects to enterprise-level apps.

Mastering Django models is the first major step in becoming a proficient Django developer.