Django
Beginner
1 min read
Defining Django Models and Fields
Example
# 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(max_length=100, unique=True)
class Meta:
verbose_name_plural = 'categories'
ordering = ['name']
def __str__(self):
return self.name
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(max_length=200, unique_for_date='published_at')
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True)
body = models.TextField()
status = models.CharField(max_length=10, 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 = ['-published_at']
indexes = [models.Index(fields=['-published_at'])]
def __str__(self):
return self.title
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