Django models are Python classes that define the structure of your database tables. Each model class maps to a single database table, and each attribute of the class represents a field in the table.
Django
Beginner
10 min read
Django Models
Example
# blog/models.py
from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
class Meta:
verbose_name_plural = 'categories'
ordering = ['name']
def __str__(self):
return self.name
class Post(models.Model):
STATUS = [('draft', 'Draft'), ('published', 'Published')]
title = models.CharField(max_length=200)
slug = models.SlugField(unique_for_date='created_at')
author = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
body = models.TextField()
status = models.CharField(max_length=10, choices=STATUS, default='draft')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-created_at']
def __str__(self):
return self.title
# Run migrations
# python manage.py makemigrations
# python manage.py migrate
Related Resources
Django Reference
Complete tag & property list
Django How-To Guides
Step-by-step practical guides
Django Exercises
Practice what you've learned
More in Django