About Default ForeignKey Value
Use the on_delete=models.SET() attribute to set the default value for the items, when their related object is deleted, e.g.:
from django.db import models
from .models import Category, Article
def get_uncategorized():
category, created = Category.objects.get_or_create(
slug="uncategorized",
defaults={"title": "Uncategorized"},
)
return category
class Article(models.Model):
category = models.ForeignKey(
Category,
on_delete=models.SET(get_uncategorized)
)
Tips and Tricks Programming Databases 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.