For our blog application, we need a model to create Post
instances. The Post
model will have a title
, a slug
(which will improve the SEO friendliness of the blog), an author
, a body
where the content of the article is stored, a boolean publish
, when the blog post is created
, updated
and a status
.
# blog/models.py
from django.db import models
from django.urls import reverse
from django.utils import timezone
class Post(models.Model):
class Status(models.TextChoices):
DRAFT = "DF", "Draft"
PUBLISHED = "PB", "Published"
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250)
author = models.ForeignKey(
"account.User", on_delete=models.CASCADE, related_name="blog_posts"
)
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=2, choices=Status, default=Status.DRAFT)
class Meta:
ordering = ["-publish"]
indexes = [
models.Index(fields=["publish"]),
]
def __str__(self):
return self.title
Model class:
author
: is linked to our User
model with a ForeignKey
relation.body
: is a normal Django TextField()
. It is a good idea to integrate a WYSIWYG rich text editor, like CkEditor
, to improve the user experience.publish
: Here you can choose from several ways of saving the date and time of the Post instance when it is published. You can use the date and time of the location stored in your project with default=timezone.now
, or you can set the date and time to the location of the server with db_default=Now()
(from django.db.models.functions import Now
). I have chosen to use the project date and time.Meta class:
ordering
: the ordering
attribute tells Django to sort the results by the publish
field by default. The dash indicates a descending order of results.indexes
: in the Django Meta
class are used to define database indexes on one or more fields of a model to optimize query performance and ensure faster lookups.