.. index:: pair: Tests ; constraints .. _tests_constraints: ============================================ Tests **constraints** ============================================ .. seealso:: - https://docs.djangoproject.com/en/dev/ref/models/constraints - https://github.com/django/django/blob/master/docs/ref/models/constraints.txt - https://github.com/django/django/blob/master/tests - https://github.com/django/django/blob/master/tests/invalid_models_tests/test_models.py .. contents:: :depth: 3 class ConstraintsTests(TestCase): ===================================== .. code-block:: python :linenos: import unittest from django.conf import settings from django.core.checks import Error, Warning from django.core.checks.model_checks import _check_lazy_references from django.db import connection, connections, models from django.db.models.functions import Lower from django.db.models.signals import post_init from django.test import SimpleTestCase, TestCase from django.test.utils import isolate_apps, override_settings, register_lookup @isolate_apps('invalid_models_tests') class ConstraintsTests(TestCase): def test_check_constraints(self): class Model(models.Model): age = models.IntegerField() class Meta: constraints = [models.CheckConstraint(check=models.Q(age__gte=18), name='is_adult')] errors = Model.check(databases=self.databases) warn = Warning( '%s does not support check constraints.' % connection.display_name, hint=( "A constraint won't be created. Silence this warning if you " "don't care about it." ), obj=Model, id='models.W027', ) expected = [] if connection.features.supports_table_check_constraints else [warn] self.assertCountEqual(errors, expected) def test_check_constraints_required_db_features(self): class Model(models.Model): age = models.IntegerField() class Meta: required_db_features = {'supports_table_check_constraints'} constraints = [models.CheckConstraint(check=models.Q(age__gte=18), name='is_adult')] self.assertEqual(Model.check(databases=self.databases), [])