Core Concepts
Models and ORM
Define your data models and use Django's ORM to query the database with Python.
Django Models
Models are Python classes that define your database schema. Each model maps to a database table.
Field Types
Common Django field types:
CharField,TextField— stringsIntegerField,FloatField— numbersBooleanField— true/falseDateField,DateTimeField— datesForeignKey,ManyToManyField,OneToOneField— relationshipsImageField,FileField— uploads
QuerySet API
Django's ORM provides a powerful, chainable API for database queries. QuerySets are lazy — they don't hit the database until evaluated.
Example
python
# blog/models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class Category(models.Model):
name = models.CharField(max_length=100, unique=True)
slug = models.SlugField(unique=True)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "categories"
class Post(models.Model):
STATUS_DRAFT = 'draft'
STATUS_PUBLISHED = 'published'
STATUS_CHOICES = [
(STATUS_DRAFT, 'Draft'),
(STATUS_PUBLISHED, 'Published'),
]
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
content = models.TextField()
excerpt = models.TextField(blank=True)
status = models.CharField(max_length=20, choices=STATUS_CHOICES, default=STATUS_DRAFT)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
published_at = models.DateTimeField(null=True, blank=True)
class Meta:
ordering = ['-created_at']
def __str__(self):
return self.title
# QuerySet examples
all_posts = Post.objects.all()
published = Post.objects.filter(status='published')
by_author = Post.objects.filter(author__username='alice')
recent = Post.objects.order_by('-created_at')[:10]
single = Post.objects.get(slug='my-first-post') # raises if not found
or_none = Post.objects.filter(slug='xyz').first() # None if not found
# Complex queries
from django.db.models import Q, Count
popular = Post.objects.filter(
Q(status='published') & Q(category__name='Django')
).annotate(comment_count=Count('comments')).order_by('-comment_count')Try it yourself — PYTHON