Overview

Django 2.2, released on April 1, 2019, is an LTS (Long Term Support) release that will receive security fixes for three years. Its headline feature is the introduction of database constraints (CheckConstraint and UniqueConstraint) directly in Django models. This release also adds the --database flag to several management commands.

Key Features

Database constraints

The Meta.constraints option allows declaring constraints directly in the model. CheckConstraint validates a condition at the database level, while UniqueConstraint offers more flexibility than unique_together by supporting conditions and include columns.

python
from django.db import models
from django.db.models import Q, CheckConstraint, UniqueConstraint

class Booking(models.Model):
    room = models.CharField(max_length=50)
    date = models.DateField()
    start_time = models.TimeField()
    end_time = models.TimeField()
    num_guests = models.PositiveIntegerField()

    class Meta:
        constraints = [
            # End time must be after start time
            CheckConstraint(
                check=Q(end_time__gt=models.F('start_time')),
                name='booking_end_after_start',
            ),
            # At least 1 guest per booking
            CheckConstraint(
                check=Q(num_guests__gte=1),
                name='booking_min_guests',
            ),
            # One booking per room, date, and time slot
            UniqueConstraint(
                fields=['room', 'date', 'start_time'],
                name='booking_unique_slot',
            ),
        ]

--database flag

The migrate, showmigrations, and other management commands now accept the --database flag to target a specific database. This is essential for multi-database projects that use database routers.

python
# Apply migrations only on the 'analytics' database
# python manage.py migrate --database=analytics

# Check migration status on the 'legacy' database
# python manage.py showmigrations --database=legacy

# Dump the 'analytics' database
# python manage.py dumpdata --database=analytics > analytics.json

# Multi-database configuration example
# settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'main_app',
    },
    'analytics': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'analytics_app',
    },
}

Sources