Django Models and ORM

Models define your data structure. Django's ORM translates Python classes into database tables.

Define a Model

Python
# blog/models.py
from django.db import models

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

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return self.title

Migrate

Bash
python manage.py makemigrations
python manage.py migrate

Query the Database

Python
from blog.models import Post

Post.objects.create(title='First Post', content='Hello!', author='Ram')
Post.objects.filter(published=True)
Post.objects.get(pk=1)
Post.objects.filter(author='Ram').order_by('-created_at')

Tips

  • Models are your single source of truth.
  • Use ForeignKey for relationships.
  • Always run makemigrations then migrate after changing models.

Next: views.