About Ensuring Mandatory Data Entries
One of the ways to ensure that the database has particular data entries is to use post_migrate signal to create those entries:
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
from django.db.models.signals import post_migrate
class PostsConfig(AppConfig):
name = "myproject.apps.posts"
verbose_name = _("Posts")
def ready(self):
post_migrate.connect(self._create_defaults, sender=self)
def _create_defaults(self, sender, **kwargs):
from .models import Category
Category.objects.get_or_create(
slug="uncategorized",
defaults={"title": "Uncategorized"}
)
The benefit of this way compared to a data migration is that you can improve or expand the data created over time without creating new migrations and that you can create data entries for third-party apps too.
Tips and Tricks Programming Django 6.x Django 5.2 Django 4.2
Also by me
Django Messaging 🎅🏼
For Django-based social platforms.
Django Paddle Subscriptions 🎅🏼
For Django-based SaaS projects.
Django GDPR Cookie Consent 🎅🏼
For Django websites that use cookies.