1. from datetime import datetime
    
  2. 
    
  3. from django.core.exceptions import ValidationError
    
  4. from django.db import models
    
  5. from django.db.models.functions import Lower
    
  6. 
    
  7. 
    
  8. def validate_answer_to_universe(value):
    
  9.     if value != 42:
    
  10.         raise ValidationError(
    
  11.             "This is not the answer to life, universe and everything!", code="not42"
    
  12.         )
    
  13. 
    
  14. 
    
  15. class ModelToValidate(models.Model):
    
  16.     name = models.CharField(max_length=100)
    
  17.     created = models.DateTimeField(default=datetime.now)
    
  18.     number = models.IntegerField(db_column="number_val")
    
  19.     parent = models.ForeignKey(
    
  20.         "self",
    
  21.         models.SET_NULL,
    
  22.         blank=True,
    
  23.         null=True,
    
  24.         limit_choices_to={"number": 10},
    
  25.     )
    
  26.     email = models.EmailField(blank=True)
    
  27.     ufm = models.ForeignKey(
    
  28.         "UniqueFieldsModel",
    
  29.         models.SET_NULL,
    
  30.         to_field="unique_charfield",
    
  31.         blank=True,
    
  32.         null=True,
    
  33.     )
    
  34.     url = models.URLField(blank=True)
    
  35.     f_with_custom_validator = models.IntegerField(
    
  36.         blank=True, null=True, validators=[validate_answer_to_universe]
    
  37.     )
    
  38.     f_with_iterable_of_validators = models.IntegerField(
    
  39.         blank=True, null=True, validators=(validate_answer_to_universe,)
    
  40.     )
    
  41.     slug = models.SlugField(blank=True)
    
  42. 
    
  43.     def clean(self):
    
  44.         super().clean()
    
  45.         if self.number == 11:
    
  46.             raise ValidationError("Invalid number supplied!")
    
  47. 
    
  48. 
    
  49. class UniqueFieldsModel(models.Model):
    
  50.     unique_charfield = models.CharField(max_length=100, unique=True)
    
  51.     unique_integerfield = models.IntegerField(unique=True)
    
  52.     non_unique_field = models.IntegerField()
    
  53. 
    
  54. 
    
  55. class CustomPKModel(models.Model):
    
  56.     my_pk_field = models.CharField(max_length=100, primary_key=True)
    
  57. 
    
  58. 
    
  59. class UniqueTogetherModel(models.Model):
    
  60.     cfield = models.CharField(max_length=100)
    
  61.     ifield = models.IntegerField()
    
  62.     efield = models.EmailField()
    
  63. 
    
  64.     class Meta:
    
  65.         unique_together = (
    
  66.             (
    
  67.                 "ifield",
    
  68.                 "cfield",
    
  69.             ),
    
  70.             ["ifield", "efield"],
    
  71.         )
    
  72. 
    
  73. 
    
  74. class UniqueForDateModel(models.Model):
    
  75.     start_date = models.DateField()
    
  76.     end_date = models.DateTimeField()
    
  77.     count = models.IntegerField(
    
  78.         unique_for_date="start_date", unique_for_year="end_date"
    
  79.     )
    
  80.     order = models.IntegerField(unique_for_month="end_date")
    
  81.     name = models.CharField(max_length=100)
    
  82. 
    
  83. 
    
  84. class CustomMessagesModel(models.Model):
    
  85.     other = models.IntegerField(blank=True, null=True)
    
  86.     number = models.IntegerField(
    
  87.         db_column="number_val",
    
  88.         error_messages={"null": "NULL", "not42": "AAARGH", "not_equal": "%s != me"},
    
  89.         validators=[validate_answer_to_universe],
    
  90.     )
    
  91. 
    
  92. 
    
  93. class AuthorManager(models.Manager):
    
  94.     def get_queryset(self):
    
  95.         qs = super().get_queryset()
    
  96.         return qs.filter(archived=False)
    
  97. 
    
  98. 
    
  99. class Author(models.Model):
    
  100.     name = models.CharField(max_length=100)
    
  101.     archived = models.BooleanField(default=False)
    
  102. 
    
  103.     objects = AuthorManager()
    
  104. 
    
  105. 
    
  106. class Article(models.Model):
    
  107.     title = models.CharField(max_length=100)
    
  108.     author = models.ForeignKey(Author, models.CASCADE)
    
  109.     pub_date = models.DateTimeField(blank=True)
    
  110. 
    
  111.     def clean(self):
    
  112.         if self.pub_date is None:
    
  113.             self.pub_date = datetime.now()
    
  114. 
    
  115. 
    
  116. class Post(models.Model):
    
  117.     title = models.CharField(max_length=50, unique_for_date="posted", blank=True)
    
  118.     slug = models.CharField(max_length=50, unique_for_year="posted", blank=True)
    
  119.     subtitle = models.CharField(max_length=50, unique_for_month="posted", blank=True)
    
  120.     posted = models.DateField()
    
  121. 
    
  122. 
    
  123. class FlexibleDatePost(models.Model):
    
  124.     title = models.CharField(max_length=50, unique_for_date="posted", blank=True)
    
  125.     slug = models.CharField(max_length=50, unique_for_year="posted", blank=True)
    
  126.     subtitle = models.CharField(max_length=50, unique_for_month="posted", blank=True)
    
  127.     posted = models.DateField(blank=True, null=True)
    
  128. 
    
  129. 
    
  130. class UniqueErrorsModel(models.Model):
    
  131.     name = models.CharField(
    
  132.         max_length=100,
    
  133.         unique=True,
    
  134.         error_messages={"unique": "Custom unique name message."},
    
  135.     )
    
  136.     no = models.IntegerField(
    
  137.         unique=True, error_messages={"unique": "Custom unique number message."}
    
  138.     )
    
  139. 
    
  140. 
    
  141. class GenericIPAddressTestModel(models.Model):
    
  142.     generic_ip = models.GenericIPAddressField(blank=True, null=True, unique=True)
    
  143.     v4_ip = models.GenericIPAddressField(blank=True, null=True, protocol="ipv4")
    
  144.     v6_ip = models.GenericIPAddressField(blank=True, null=True, protocol="ipv6")
    
  145.     ip_verbose_name = models.GenericIPAddressField(
    
  146.         "IP Address Verbose", blank=True, null=True
    
  147.     )
    
  148. 
    
  149. 
    
  150. class GenericIPAddrUnpackUniqueTest(models.Model):
    
  151.     generic_v4unpack_ip = models.GenericIPAddressField(
    
  152.         null=True, blank=True, unique=True, unpack_ipv4=True
    
  153.     )
    
  154. 
    
  155. 
    
  156. class UniqueFuncConstraintModel(models.Model):
    
  157.     field = models.CharField(max_length=255)
    
  158. 
    
  159.     class Meta:
    
  160.         required_db_features = {"supports_expression_indexes"}
    
  161.         constraints = [
    
  162.             models.UniqueConstraint(Lower("field"), name="func_lower_field_uq"),
    
  163.         ]
    
  164. 
    
  165. 
    
  166. class Product(models.Model):
    
  167.     price = models.IntegerField(null=True)
    
  168.     discounted_price = models.IntegerField(null=True)
    
  169. 
    
  170.     class Meta:
    
  171.         required_db_features = {
    
  172.             "supports_table_check_constraints",
    
  173.         }
    
  174.         constraints = [
    
  175.             models.CheckConstraint(
    
  176.                 check=models.Q(price__gt=models.F("discounted_price")),
    
  177.                 name="price_gt_discounted_price_validation",
    
  178.             ),
    
  179.         ]
    
  180. 
    
  181. 
    
  182. class ChildProduct(Product):
    
  183.     class Meta:
    
  184.         required_db_features = {
    
  185.             "supports_table_check_constraints",
    
  186.         }
    
  187. 
    
  188. 
    
  189. class UniqueConstraintProduct(models.Model):
    
  190.     name = models.CharField(max_length=255)
    
  191.     color = models.CharField(max_length=32)
    
  192.     rank = models.IntegerField()
    
  193. 
    
  194.     class Meta:
    
  195.         constraints = [
    
  196.             models.UniqueConstraint(
    
  197.                 fields=["name", "color"], name="name_color_uniq_validation"
    
  198.             ),
    
  199.             models.UniqueConstraint(fields=["rank"], name="rank_uniq_validation"),
    
  200.         ]
    
  201. 
    
  202. 
    
  203. class ChildUniqueConstraintProduct(UniqueConstraintProduct):
    
  204.     pass
    
  205. 
    
  206. 
    
  207. class UniqueConstraintConditionProduct(models.Model):
    
  208.     name = models.CharField(max_length=255)
    
  209.     color = models.CharField(max_length=31, null=True, blank=True)
    
  210. 
    
  211.     class Meta:
    
  212.         required_db_features = {"supports_partial_indexes"}
    
  213.         constraints = [
    
  214.             models.UniqueConstraint(
    
  215.                 fields=["name"],
    
  216.                 name="name_without_color_uniq_validation",
    
  217.                 condition=models.Q(color__isnull=True),
    
  218.             ),
    
  219.         ]