Labs ICT
Pro Login

Models

Defining your data as Python classes.

What Are Models?

Models are the heart of your data layer in Django. Each model maps directly to a database table, and each attribute becomes a column. You define your data structure in Python, and Django handles the SQL for you.

No need to write CREATE TABLE statements. No need to deal with raw SQL for basic operations. Django's ORM does the heavy lifting.

Defining a Model

Let's create a simple blog post model. Open models.py in your app and add this:


from django.db import models

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

Each field type tells Django what kind of data to expect. CharField is for short text, TextField is for long content, and BooleanField is for true/false values.

Try it Yourself →

The Meta Class and __str__

You can customize how Django treats your model using the inner Meta class and the __str__ method:


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

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['-created_at']
        verbose_name = 'Blog Post'
        verbose_name_plural = 'Blog Posts'
    

The __str__ method makes your model readable in the admin and shell. The Meta class controls default ordering and display names. Trust me, you'll use these constantly.

How Models Map to Tables

Django automatically converts your model class into a database table. The table name follows the pattern appname_modelname. So a Post model in the blog app becomes the blog_post table.

Each field becomes a column with the appropriate data type. Your CharField(max_length=200) becomes a VARCHAR(200) in the database. This abstraction means you can switch databases without rewriting your models.