Debian Codegraph @

tests/invalid_models_tests/test_models.py

raw
1 import unittest
2
3 from django.core.checks import Error, Warning
4 from django.core.checks.model_checks import _check_lazy_references
5 from django.db import connection, connections, models
6 from django.db.models.functions import Abs, Lower, Round
7 from django.db.models.signals import post_init
8 from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature
9 from django.test.utils import isolate_apps, override_settings, register_lookup
10
11
12 class EmptyRouter:
13 pass
14
15
16 def get_max_column_name_length():
17 allowed_len = None
18 db_alias = None
19
20 for db in ("default", "other"):
21 connection = connections[db]
22 max_name_length = connection.ops.max_name_length()
23 if max_name_length is not None and not connection.features.truncates_names:
24 if allowed_len is None or max_name_length < allowed_len:
25 allowed_len = max_name_length
26 db_alias = db
27
28 return (allowed_len, db_alias)
29
30
31 @isolate_apps("invalid_models_tests")
32 class UniqueTogetherTests(SimpleTestCase):
33 def test_non_iterable(self):
34 class Model(models.Model):
35 class Meta:
36 unique_together = 42
37
38 self.assertEqual(
39 Model.check(),
40 [
41 Error(
42 "'unique_together' must be a list or tuple.",
43 obj=Model,
44 id="models.E010",
45 ),
46 ],
47 )
48
49 def test_list_containing_non_iterable(self):
50 class Model(models.Model):
51 one = models.IntegerField()
52 two = models.IntegerField()
53
54 class Meta:
55 unique_together = [("a", "b"), 42]
56
57 self.assertEqual(
58 Model.check(),
59 [
60 Error(
61 "All 'unique_together' elements must be lists or tuples.",
62 obj=Model,
63 id="models.E011",
64 ),
65 ],
66 )
67
68 def test_non_list(self):
69 class Model(models.Model):
70 class Meta:
71 unique_together = "not-a-list"
72
73 self.assertEqual(
74 Model.check(),
75 [
76 Error(
77 "'unique_together' must be a list or tuple.",
78 obj=Model,
79 id="models.E010",
80 ),
81 ],
82 )
83
84 def test_valid_model(self):
85 class Model(models.Model):
86 one = models.IntegerField()
87 two = models.IntegerField()
88
89 class Meta:
90 # unique_together can be a simple tuple
91 unique_together = ("one", "two")
92
93 self.assertEqual(Model.check(), [])
94
95 def test_pointing_to_missing_field(self):
96 class Model(models.Model):
97 class Meta:
98 unique_together = [["missing_field"]]
99
100 self.assertEqual(
101 Model.check(),
102 [
103 Error(
104 "'unique_together' refers to the nonexistent field "
105 "'missing_field'.",
106 obj=Model,
107 id="models.E012",
108 ),
109 ],
110 )
111
112 def test_pointing_to_m2m(self):
113 class Model(models.Model):
114 m2m = models.ManyToManyField("self")
115
116 class Meta:
117 unique_together = [["m2m"]]
118
119 self.assertEqual(
120 Model.check(),
121 [
122 Error(
123 "'unique_together' refers to a ManyToManyField 'm2m', but "
124 "ManyToManyFields are not permitted in 'unique_together'.",
125 obj=Model,
126 id="models.E013",
127 ),
128 ],
129 )
130
131 def test_pointing_to_fk(self):
132 class Foo(models.Model):
133 pass
134
135 class Bar(models.Model):
136 foo_1 = models.ForeignKey(
137 Foo, on_delete=models.CASCADE, related_name="bar_1"
138 )
139 foo_2 = models.ForeignKey(
140 Foo, on_delete=models.CASCADE, related_name="bar_2"
141 )
142
143 class Meta:
144 unique_together = [["foo_1_id", "foo_2"]]
145
146 self.assertEqual(Bar.check(), [])
147
148 def test_pointing_to_composite_primary_key(self):
149 class Model(models.Model):
150 pk = models.CompositePrimaryKey("version", "name")
151 version = models.IntegerField()
152 name = models.CharField(max_length=20)
153
154 class Meta:
155 unique_together = [["pk"]]
156
157 self.assertEqual(
158 Model.check(),
159 [
160 Error(
161 "'unique_together' refers to a CompositePrimaryKey 'pk', but "
162 "CompositePrimaryKeys are not permitted in 'unique_together'.",
163 obj=Model,
164 id="models.E048",
165 ),
166 ],
167 )
168
169
170 @isolate_apps("invalid_models_tests")
171 class IndexesTests(TestCase):
172 def test_pointing_to_missing_field(self):
173 class Model(models.Model):
174 class Meta:
175 indexes = [models.Index(fields=["missing_field"], name="name")]
176
177 self.assertEqual(
178 Model.check(),
179 [
180 Error(
181 "'indexes' refers to the nonexistent field 'missing_field'.",
182 obj=Model,
183 id="models.E012",
184 ),
185 ],
186 )
187
188 def test_pointing_to_m2m_field(self):
189 class Model(models.Model):
190 m2m = models.ManyToManyField("self")
191
192 class Meta:
193 indexes = [models.Index(fields=["m2m"], name="name")]
194
195 self.assertEqual(
196 Model.check(),
197 [
198 Error(
199 "'indexes' refers to a ManyToManyField 'm2m', but "
200 "ManyToManyFields are not permitted in 'indexes'.",
201 obj=Model,
202 id="models.E013",
203 ),
204 ],
205 )
206
207 def test_pointing_to_non_local_field(self):
208 class Foo(models.Model):
209 field1 = models.IntegerField()
210
211 class Bar(Foo):
212 field2 = models.IntegerField()
213
214 class Meta:
215 indexes = [models.Index(fields=["field2", "field1"], name="name")]
216
217 self.assertEqual(
218 Bar.check(),
219 [
220 Error(
221 "'indexes' refers to field 'field1' which is not local to "
222 "model 'Bar'.",
223 hint="This issue may be caused by multi-table inheritance.",
224 obj=Bar,
225 id="models.E016",
226 ),
227 ],
228 )
229
230 def test_pointing_to_fk(self):
231 class Foo(models.Model):
232 pass
233
234 class Bar(models.Model):
235 foo_1 = models.ForeignKey(
236 Foo, on_delete=models.CASCADE, related_name="bar_1"
237 )
238 foo_2 = models.ForeignKey(
239 Foo, on_delete=models.CASCADE, related_name="bar_2"
240 )
241
242 class Meta:
243 indexes = [
244 models.Index(fields=["foo_1_id", "foo_2"], name="index_name")
245 ]
246
247 self.assertEqual(Bar.check(), [])
248
249 def test_pointing_to_composite_primary_key(self):
250 class Model(models.Model):
251 pk = models.CompositePrimaryKey("version", "name")
252 version = models.IntegerField()
253 name = models.CharField(max_length=20)
254
255 class Meta:
256 indexes = [models.Index(fields=["pk", "name"], name="name")]
257
258 self.assertEqual(
259 Model.check(),
260 [
261 Error(
262 "'indexes' refers to a CompositePrimaryKey 'pk', but "
263 "CompositePrimaryKeys are not permitted in 'indexes'.",
264 obj=Model,
265 id="models.E048",
266 ),
267 ],
268 )
269
270 def test_name_constraints(self):
271 class Model(models.Model):
272 class Meta:
273 indexes = [
274 models.Index(fields=["id"], name="_index_name"),
275 models.Index(fields=["id"], name="5index_name"),
276 ]
277
278 self.assertEqual(
279 Model.check(),
280 [
281 Error(
282 "The index name '%sindex_name' cannot start with an "
283 "underscore or a number." % prefix,
284 obj=Model,
285 id="models.E033",
286 )
287 for prefix in ("_", "5")
288 ],
289 )
290
291 def test_max_name_length(self):
292 index_name = "x" * 31
293
294 class Model(models.Model):
295 class Meta:
296 indexes = [models.Index(fields=["id"], name=index_name)]
297
298 self.assertEqual(
299 Model.check(),
300 [
301 Error(
302 "The index name '%s' cannot be longer than 30 characters."
303 % index_name,
304 obj=Model,
305 id="models.E034",
306 ),
307 ],
308 )
309
310 def test_index_with_condition(self):
311 class Model(models.Model):
312 age = models.IntegerField()
313
314 class Meta:
315 indexes = [
316 models.Index(
317 fields=["age"],
318 name="index_age_gte_10",
319 condition=models.Q(age__gte=10),
320 ),
321 ]
322
323 errors = Model.check(databases=self.databases)
324 expected = (
325 []
326 if connection.features.supports_partial_indexes
327 else [
328 Warning(
329 "%s does not support indexes with conditions."
330 % connection.display_name,
331 hint=(
332 "Conditions will be ignored. Silence this warning if you "
333 "don't care about it."
334 ),
335 obj=Model,
336 id="models.W037",
337 )
338 ]
339 )
340 self.assertEqual(errors, expected)
341
342 def test_index_with_condition_required_db_features(self):
343 class Model(models.Model):
344 age = models.IntegerField()
345
346 class Meta:
347 required_db_features = {"supports_partial_indexes"}
348 indexes = [
349 models.Index(
350 fields=["age"],
351 name="index_age_gte_10",
352 condition=models.Q(age__gte=10),
353 ),
354 ]
355
356 self.assertEqual(Model.check(databases=self.databases), [])
357
358 def test_index_with_include(self):
359 class Model(models.Model):
360 age = models.IntegerField()
361
362 class Meta:
363 indexes = [
364 models.Index(
365 fields=["age"],
366 name="index_age_include_id",
367 include=["id"],
368 ),
369 ]
370
371 errors = Model.check(databases=self.databases)
372 expected = (
373 []
374 if connection.features.supports_covering_indexes
375 else [
376 Warning(
377 "%s does not support indexes with non-key columns."
378 % connection.display_name,
379 hint=(
380 "Non-key columns will be ignored. Silence this warning if "
381 "you don't care about it."
382 ),
383 obj=Model,
384 id="models.W040",
385 )
386 ]
387 )
388 self.assertEqual(errors, expected)
389
390 def test_index_with_include_required_db_features(self):
391 class Model(models.Model):
392 age = models.IntegerField()
393
394 class Meta:
395 required_db_features = {"supports_covering_indexes"}
396 indexes = [
397 models.Index(
398 fields=["age"],
399 name="index_age_include_id",
400 include=["id"],
401 ),
402 ]
403
404 self.assertEqual(Model.check(databases=self.databases), [])
405
406 @skipUnlessDBFeature("supports_covering_indexes")
407 def test_index_include_pointing_to_missing_field(self):
408 class Model(models.Model):
409 class Meta:
410 indexes = [
411 models.Index(fields=["id"], include=["missing_field"], name="name"),
412 ]
413
414 self.assertEqual(
415 Model.check(databases=self.databases),
416 [
417 Error(
418 "'indexes' refers to the nonexistent field 'missing_field'.",
419 obj=Model,
420 id="models.E012",
421 ),
422 ],
423 )
424
425 @skipUnlessDBFeature("supports_covering_indexes")
426 def test_index_include_pointing_to_m2m_field(self):
427 class Model(models.Model):
428 m2m = models.ManyToManyField("self")
429
430 class Meta:
431 indexes = [models.Index(fields=["id"], include=["m2m"], name="name")]
432
433 self.assertEqual(
434 Model.check(databases=self.databases),
435 [
436 Error(
437 "'indexes' refers to a ManyToManyField 'm2m', but "
438 "ManyToManyFields are not permitted in 'indexes'.",
439 obj=Model,
440 id="models.E013",
441 ),
442 ],
443 )
444
445 @skipUnlessDBFeature("supports_covering_indexes")
446 def test_index_include_pointing_to_non_local_field(self):
447 class Parent(models.Model):
448 field1 = models.IntegerField()
449
450 class Child(Parent):
451 field2 = models.IntegerField()
452
453 class Meta:
454 indexes = [
455 models.Index(fields=["field2"], include=["field1"], name="name"),
456 ]
457
458 self.assertEqual(
459 Child.check(databases=self.databases),
460 [
461 Error(
462 "'indexes' refers to field 'field1' which is not local to "
463 "model 'Child'.",
464 hint="This issue may be caused by multi-table inheritance.",
465 obj=Child,
466 id="models.E016",
467 ),
468 ],
469 )
470
471 @skipUnlessDBFeature("supports_covering_indexes")
472 def test_index_include_pointing_to_fk(self):
473 class Target(models.Model):
474 pass
475
476 class Model(models.Model):
477 fk_1 = models.ForeignKey(Target, models.CASCADE, related_name="target_1")
478 fk_2 = models.ForeignKey(Target, models.CASCADE, related_name="target_2")
479
480 class Meta:
481 indexes = [
482 models.Index(
483 fields=["id"],
484 include=["fk_1_id", "fk_2"],
485 name="name",
486 ),
487 ]
488
489 self.assertEqual(Model.check(databases=self.databases), [])
490
491 @skipUnlessDBFeature("supports_covering_indexes")
492 def test_index_include_pointing_to_composite_primary_key(self):
493 class Model(models.Model):
494 pk = models.CompositePrimaryKey("version", "name")
495 version = models.IntegerField()
496 name = models.CharField(max_length=20)
497
498 class Meta:
499 indexes = [models.Index(fields=["name"], include=["pk"], name="name")]
500
501 self.assertEqual(
502 Model.check(),
503 [
504 Error(
505 "'indexes' refers to a CompositePrimaryKey 'pk', but "
506 "CompositePrimaryKeys are not permitted in 'indexes'.",
507 obj=Model,
508 id="models.E048",
509 ),
510 ],
511 )
512
513 def test_func_index(self):
514 class Model(models.Model):
515 name = models.CharField(max_length=10)
516
517 class Meta:
518 indexes = [models.Index(Lower("name"), name="index_lower_name")]
519
520 warn = Warning(
521 "%s does not support indexes on expressions." % connection.display_name,
522 hint=(
523 "An index won't be created. Silence this warning if you don't "
524 "care about it."
525 ),
526 obj=Model,
527 id="models.W043",
528 )
529 expected = [] if connection.features.supports_expression_indexes else [warn]
530 self.assertEqual(Model.check(databases=self.databases), expected)
531
532 def test_func_index_required_db_features(self):
533 class Model(models.Model):
534 name = models.CharField(max_length=10)
535
536 class Meta:
537 indexes = [models.Index(Lower("name"), name="index_lower_name")]
538 required_db_features = {"supports_expression_indexes"}
539
540 self.assertEqual(Model.check(databases=self.databases), [])
541
542 def test_func_index_complex_expression_custom_lookup(self):
543 class Model(models.Model):
544 height = models.IntegerField()
545 weight = models.IntegerField()
546
547 class Meta:
548 indexes = [
549 models.Index(
550 models.F("height")
551 / (models.F("weight__abs") + models.Value(5)),
552 name="name",
553 ),
554 ]
555
556 with register_lookup(models.IntegerField, Abs):
557 self.assertEqual(Model.check(), [])
558
559 def test_func_index_pointing_to_missing_field(self):
560 class Model(models.Model):
561 class Meta:
562 indexes = [models.Index(Lower("missing_field").desc(), name="name")]
563
564 self.assertEqual(
565 Model.check(),
566 [
567 Error(
568 "'indexes' refers to the nonexistent field 'missing_field'.",
569 obj=Model,
570 id="models.E012",
571 ),
572 ],
573 )
574
575 def test_func_index_pointing_to_missing_field_nested(self):
576 class Model(models.Model):
577 class Meta:
578 indexes = [
579 models.Index(Abs(Round("missing_field")), name="name"),
580 ]
581
582 self.assertEqual(
583 Model.check(),
584 [
585 Error(
586 "'indexes' refers to the nonexistent field 'missing_field'.",
587 obj=Model,
588 id="models.E012",
589 ),
590 ],
591 )
592
593 def test_func_index_pointing_to_m2m_field(self):
594 class Model(models.Model):
595 m2m = models.ManyToManyField("self")
596
597 class Meta:
598 indexes = [models.Index(Lower("m2m"), name="name")]
599
600 self.assertEqual(
601 Model.check(),
602 [
603 Error(
604 "'indexes' refers to a ManyToManyField 'm2m', but "
605 "ManyToManyFields are not permitted in 'indexes'.",
606 obj=Model,
607 id="models.E013",
608 ),
609 ],
610 )
611
612 def test_func_index_pointing_to_non_local_field(self):
613 class Foo(models.Model):
614 field1 = models.CharField(max_length=15)
615
616 class Bar(Foo):
617 class Meta:
618 indexes = [models.Index(Lower("field1"), name="name")]
619
620 self.assertEqual(
621 Bar.check(),
622 [
623 Error(
624 "'indexes' refers to field 'field1' which is not local to "
625 "model 'Bar'.",
626 hint="This issue may be caused by multi-table inheritance.",
627 obj=Bar,
628 id="models.E016",
629 ),
630 ],
631 )
632
633 def test_func_index_pointing_to_fk(self):
634 class Foo(models.Model):
635 pass
636
637 class Bar(models.Model):
638 foo_1 = models.ForeignKey(Foo, models.CASCADE, related_name="bar_1")
639 foo_2 = models.ForeignKey(Foo, models.CASCADE, related_name="bar_2")
640
641 class Meta:
642 indexes = [
643 models.Index(Lower("foo_1_id"), Lower("foo_2"), name="index_name"),
644 ]
645
646 self.assertEqual(Bar.check(), [])
647
648 def test_func_index_pointing_to_composite_primary_key(self):
649 class Model(models.Model):
650 pk = models.CompositePrimaryKey("version", "name")
651 version = models.IntegerField()
652 name = models.CharField(max_length=20)
653
654 class Meta:
655 indexes = [models.Index(Abs("pk"), name="name")]
656
657 self.assertEqual(
658 Model.check(),
659 [
660 Error(
661 "'indexes' refers to a CompositePrimaryKey 'pk', but "
662 "CompositePrimaryKeys are not permitted in 'indexes'.",
663 obj=Model,
664 id="models.E048",
665 ),
666 ],
667 )
668
669
670 @isolate_apps("invalid_models_tests")
671 class FieldNamesTests(TestCase):
672 databases = {"default", "other"}
673
674 def test_ending_with_underscore(self):
675 class Model(models.Model):
676 field_ = models.CharField(max_length=10)
677 m2m_ = models.ManyToManyField("self")
678
679 self.assertEqual(
680 Model.check(),
681 [
682 Error(
683 "Field names must not end with an underscore.",
684 obj=Model._meta.get_field("field_"),
685 id="fields.E001",
686 ),
687 Error(
688 "Field names must not end with an underscore.",
689 obj=Model._meta.get_field("m2m_"),
690 id="fields.E001",
691 ),
692 ],
693 )
694
695 max_column_name_length, column_limit_db_alias = get_max_column_name_length()
696
697 @unittest.skipIf(
698 max_column_name_length is None,
699 "The database doesn't have a column name length limit.",
700 )
701 def test_M2M_long_column_name(self):
702 """
703 #13711 -- Model check for long M2M column names when database has
704 column name length limits.
705 """
706
707 # A model with very long name which will be used to set relations to.
708 class VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz(
709 models.Model
710 ):
711 title = models.CharField(max_length=11)
712
713 # Main model for which checks will be performed.
714 class ModelWithLongField(models.Model):
715 m2m_field = models.ManyToManyField(
716 VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz,
717 related_name="rn1",
718 )
719 m2m_field2 = models.ManyToManyField(
720 VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz,
721 related_name="rn2",
722 through="m2msimple",
723 )
724 m2m_field3 = models.ManyToManyField(
725 VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz,
726 related_name="rn3",
727 through="m2mcomplex",
728 )
729 fk = models.ForeignKey(
730 VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz,
731 models.CASCADE,
732 related_name="rn4",
733 )
734
735 # Models used for setting `through` in M2M field.
736 class m2msimple(models.Model):
737 id2 = models.ForeignKey(ModelWithLongField, models.CASCADE)
738
739 class m2mcomplex(models.Model):
740 id2 = models.ForeignKey(ModelWithLongField, models.CASCADE)
741
742 long_field_name = "a" * (self.max_column_name_length + 1)
743 models.ForeignKey(
744 VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz,
745 models.CASCADE,
746 ).contribute_to_class(m2msimple, long_field_name)
747
748 models.ForeignKey(
749 VeryLongModelNamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz,
750 models.CASCADE,
751 db_column=long_field_name,
752 ).contribute_to_class(m2mcomplex, long_field_name)
753
754 errors = ModelWithLongField.check(databases=("default", "other"))
755
756 # First error because of M2M field set on the model with long name.
757 m2m_long_name = (
758 "verylongmodelnamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz_id"
759 )
760 if self.max_column_name_length > len(m2m_long_name):
761 # Some databases support names longer than the test name.
762 expected = []
763 else:
764 expected = [
765 Error(
766 'Autogenerated column name too long for M2M field "%s". '
767 'Maximum length is "%s" for database "%s".'
768 % (
769 m2m_long_name,
770 self.max_column_name_length,
771 self.column_limit_db_alias,
772 ),
773 hint="Use 'through' to create a separate model for "
774 "M2M and then set column_name using 'db_column'.",
775 obj=ModelWithLongField,
776 id="models.E019",
777 )
778 ]
779
780 # Second error because the FK specified in the `through` model
781 # `m2msimple` has auto-generated name longer than allowed.
782 # There will be no check errors in the other M2M because it
783 # specifies db_column for the FK in `through` model even if the actual
784 # name is longer than the limits of the database.
785 expected.append(
786 Error(
787 'Autogenerated column name too long for M2M field "%s_id". '
788 'Maximum length is "%s" for database "%s".'
789 % (
790 long_field_name,
791 self.max_column_name_length,
792 self.column_limit_db_alias,
793 ),
794 hint="Use 'through' to create a separate model for "
795 "M2M and then set column_name using 'db_column'.",
796 obj=ModelWithLongField,
797 id="models.E019",
798 )
799 )
800
801 self.assertEqual(errors, expected)
802 # Check for long column names is called only for specified database
803 # aliases.
804 self.assertEqual(ModelWithLongField.check(databases=None), [])
805
806 @unittest.skipIf(
807 max_column_name_length is None,
808 "The database doesn't have a column name length limit.",
809 )
810 def test_local_field_long_column_name(self):
811 """
812 #13711 -- Model check for long column names
813 when database does not support long names.
814 """
815
816 class ModelWithLongField(models.Model):
817 title = models.CharField(max_length=11)
818
819 long_field_name = "a" * (self.max_column_name_length + 1)
820 long_field_name2 = "b" * (self.max_column_name_length + 1)
821 models.CharField(max_length=11).contribute_to_class(
822 ModelWithLongField, long_field_name
823 )
824 models.CharField(max_length=11, db_column="vlmn").contribute_to_class(
825 ModelWithLongField, long_field_name2
826 )
827 self.assertEqual(
828 ModelWithLongField.check(databases=("default", "other")),
829 [
830 Error(
831 'Autogenerated column name too long for field "%s". '
832 'Maximum length is "%s" for database "%s".'
833 % (
834 long_field_name,
835 self.max_column_name_length,
836 self.column_limit_db_alias,
837 ),
838 hint="Set the column name manually using 'db_column'.",
839 obj=ModelWithLongField,
840 id="models.E018",
841 )
842 ],
843 )
844 # Check for long column names is called only for specified database
845 # aliases.
846 self.assertEqual(ModelWithLongField.check(databases=None), [])
847
848 def test_including_separator(self):
849 class Model(models.Model):
850 some__field = models.IntegerField()
851
852 self.assertEqual(
853 Model.check(),
854 [
855 Error(
856 'Field names must not contain "__".',
857 obj=Model._meta.get_field("some__field"),
858 id="fields.E002",
859 )
860 ],
861 )
862
863 def test_pk(self):
864 class Model(models.Model):
865 pk = models.IntegerField()
866
867 self.assertEqual(
868 Model.check(),
869 [
870 Error(
871 "'pk' is a reserved word that cannot be used as a field name.",
872 obj=Model._meta.get_field("pk"),
873 id="fields.E003",
874 )
875 ],
876 )
877
878 def test_db_column_clash(self):
879 class Model(models.Model):
880 foo = models.IntegerField()
881 bar = models.IntegerField(db_column="foo")
882
883 self.assertEqual(
884 Model.check(),
885 [
886 Error(
887 "Field 'bar' has column name 'foo' that is used by "
888 "another field.",
889 hint="Specify a 'db_column' for the field.",
890 obj=Model,
891 id="models.E007",
892 )
893 ],
894 )
895
896
897 @isolate_apps("invalid_models_tests")
898 class ShadowingFieldsTests(SimpleTestCase):
899 def test_field_name_clash_with_child_accessor(self):
900 class Parent(models.Model):
901 pass
902
903 class Child(Parent):
904 child = models.CharField(max_length=100)
905
906 self.assertEqual(
907 Child.check(),
908 [
909 Error(
910 "The field 'child' clashes with the field "
911 "'child' from model 'invalid_models_tests.parent'.",
912 obj=Child._meta.get_field("child"),
913 id="models.E006",
914 )
915 ],
916 )
917
918 def test_field_name_clash_with_m2m_through(self):
919 class Parent(models.Model):
920 clash_id = models.IntegerField()
921
922 class Child(Parent):
923 clash = models.ForeignKey("Child", models.CASCADE)
924
925 class Model(models.Model):
926 parents = models.ManyToManyField(
927 to=Parent,
928 through="Through",
929 through_fields=["parent", "model"],
930 )
931
932 class Through(models.Model):
933 parent = models.ForeignKey(Parent, models.CASCADE)
934 model = models.ForeignKey(Model, models.CASCADE)
935
936 self.assertEqual(
937 Child.check(),
938 [
939 Error(
940 "The field 'clash' clashes with the field 'clash_id' from "
941 "model 'invalid_models_tests.parent'.",
942 obj=Child._meta.get_field("clash"),
943 id="models.E006",
944 )
945 ],
946 )
947
948 def test_multiinheritance_clash(self):
949 class Mother(models.Model):
950 clash = models.IntegerField()
951
952 class Father(models.Model):
953 clash = models.IntegerField()
954
955 class Child(Mother, Father):
956 # Here we have two clashed: id (automatic field) and clash, because
957 # both parents define these fields.
958 pass
959
960 self.assertEqual(
961 Child.check(),
962 [
963 Error(
964 "The field 'id' from parent model "
965 "'invalid_models_tests.mother' clashes with the field 'id' "
966 "from parent model 'invalid_models_tests.father'.",
967 obj=Child,
968 id="models.E005",
969 ),
970 Error(
971 "The field 'clash' from parent model "
972 "'invalid_models_tests.mother' clashes with the field 'clash' "
973 "from parent model 'invalid_models_tests.father'.",
974 obj=Child,
975 id="models.E005",
976 ),
977 ],
978 )
979
980 def test_inheritance_clash(self):
981 class Parent(models.Model):
982 f_id = models.IntegerField()
983
984 class Target(models.Model):
985 # This field doesn't result in a clash.
986 f_id = models.IntegerField()
987
988 class Child(Parent):
989 # This field clashes with parent "f_id" field.
990 f = models.ForeignKey(Target, models.CASCADE)
991
992 self.assertEqual(
993 Child.check(),
994 [
995 Error(
996 "The field 'f' clashes with the field 'f_id' "
997 "from model 'invalid_models_tests.parent'.",
998 obj=Child._meta.get_field("f"),
999 id="models.E006",
1000 )
1001 ],
1002 )
1003
1004 def test_multigeneration_inheritance(self):
1005 class GrandParent(models.Model):
1006 clash = models.IntegerField()
1007
1008 class Parent(GrandParent):
1009 pass
1010
1011 class Child(Parent):
1012 pass
1013
1014 class GrandChild(Child):
1015 clash = models.IntegerField()
1016
1017 self.assertEqual(
1018 GrandChild.check(),
1019 [
1020 Error(
1021 "The field 'clash' clashes with the field 'clash' "
1022 "from model 'invalid_models_tests.grandparent'.",
1023 obj=GrandChild._meta.get_field("clash"),
1024 id="models.E006",
1025 )
1026 ],
1027 )
1028
1029 def test_diamond_mti_common_parent(self):
1030 class GrandParent(models.Model):
1031 pass
1032
1033 class Parent(GrandParent):
1034 pass
1035
1036 class Child(Parent):
1037 pass
1038
1039 class MTICommonParentModel(Child, GrandParent):
1040 pass
1041
1042 self.assertEqual(
1043 MTICommonParentModel.check(),
1044 [
1045 Error(
1046 "The field 'grandparent_ptr' clashes with the field "
1047 "'grandparent_ptr' from model 'invalid_models_tests.parent'.",
1048 obj=MTICommonParentModel,
1049 id="models.E006",
1050 )
1051 ],
1052 )
1053
1054 def test_id_clash(self):
1055 class Target(models.Model):
1056 pass
1057
1058 class Model(models.Model):
1059 fk = models.ForeignKey(Target, models.CASCADE)
1060 fk_id = models.IntegerField()
1061
1062 self.assertEqual(
1063 Model.check(),
1064 [
1065 Error(
1066 "The field 'fk_id' clashes with the field 'fk' from model "
1067 "'invalid_models_tests.model'.",
1068 obj=Model._meta.get_field("fk_id"),
1069 id="models.E006",
1070 )
1071 ],
1072 )
1073
1074
1075 @isolate_apps("invalid_models_tests")
1076 class OtherModelTests(SimpleTestCase):
1077 def test_unique_primary_key(self):
1078 invalid_id = models.IntegerField(primary_key=False)
1079
1080 class Model(models.Model):
1081 id = invalid_id
1082
1083 self.assertEqual(
1084 Model.check(),
1085 [
1086 Error(
1087 "'id' can only be used as a field name if the field also sets "
1088 "'primary_key=True'.",
1089 obj=Model,
1090 id="models.E004",
1091 ),
1092 ],
1093 )
1094
1095 def test_ordering_non_iterable(self):
1096 class Model(models.Model):
1097 class Meta:
1098 ordering = "missing_field"
1099
1100 self.assertEqual(
1101 Model.check(),
1102 [
1103 Error(
1104 "'ordering' must be a tuple or list "
1105 "(even if you want to order by only one field).",
1106 obj=Model,
1107 id="models.E014",
1108 ),
1109 ],
1110 )
1111
1112 def test_just_ordering_no_errors(self):
1113 class Model(models.Model):
1114 order = models.PositiveIntegerField()
1115
1116 class Meta:
1117 ordering = ["order"]
1118
1119 self.assertEqual(Model.check(), [])
1120
1121 def test_just_order_with_respect_to_no_errors(self):
1122 class Question(models.Model):
1123 pass
1124
1125 class Answer(models.Model):
1126 question = models.ForeignKey(Question, models.CASCADE)
1127
1128 class Meta:
1129 order_with_respect_to = "question"
1130
1131 self.assertEqual(Answer.check(), [])
1132
1133 def test_ordering_with_order_with_respect_to(self):
1134 class Question(models.Model):
1135 pass
1136
1137 class Answer(models.Model):
1138 question = models.ForeignKey(Question, models.CASCADE)
1139 order = models.IntegerField()
1140
1141 class Meta:
1142 order_with_respect_to = "question"
1143 ordering = ["order"]
1144
1145 self.assertEqual(
1146 Answer.check(),
1147 [
1148 Error(
1149 "'ordering' and 'order_with_respect_to' cannot be used together.",
1150 obj=Answer,
1151 id="models.E021",
1152 ),
1153 ],
1154 )
1155
1156 def test_non_valid(self):
1157 class RelationModel(models.Model):
1158 pass
1159
1160 class Model(models.Model):
1161 relation = models.ManyToManyField(RelationModel)
1162
1163 class Meta:
1164 ordering = ["relation"]
1165
1166 self.assertEqual(
1167 Model.check(),
1168 [
1169 Error(
1170 "'ordering' refers to the nonexistent field, related field, "
1171 "or lookup 'relation'.",
1172 obj=Model,
1173 id="models.E015",
1174 ),
1175 ],
1176 )
1177
1178 def test_ordering_pointing_to_missing_field(self):
1179 class Model(models.Model):
1180 class Meta:
1181 ordering = ("missing_field",)
1182
1183 self.assertEqual(
1184 Model.check(),
1185 [
1186 Error(
1187 "'ordering' refers to the nonexistent field, related field, "
1188 "or lookup 'missing_field'.",
1189 obj=Model,
1190 id="models.E015",
1191 )
1192 ],
1193 )
1194
1195 def test_ordering_pointing_to_missing_foreignkey_field(self):
1196 class Model(models.Model):
1197 missing_fk_field = models.IntegerField()
1198
1199 class Meta:
1200 ordering = ("missing_fk_field_id",)
1201
1202 self.assertEqual(
1203 Model.check(),
1204 [
1205 Error(
1206 "'ordering' refers to the nonexistent field, related field, "
1207 "or lookup 'missing_fk_field_id'.",
1208 obj=Model,
1209 id="models.E015",
1210 )
1211 ],
1212 )
1213
1214 def test_ordering_pointing_to_missing_related_field(self):
1215 class Model(models.Model):
1216 test = models.IntegerField()
1217
1218 class Meta:
1219 ordering = ("missing_related__id",)
1220
1221 self.assertEqual(
1222 Model.check(),
1223 [
1224 Error(
1225 "'ordering' refers to the nonexistent field, related field, "
1226 "or lookup 'missing_related__id'.",
1227 obj=Model,
1228 id="models.E015",
1229 )
1230 ],
1231 )
1232
1233 def test_ordering_pointing_to_missing_related_model_field(self):
1234 class Parent(models.Model):
1235 pass
1236
1237 class Child(models.Model):
1238 parent = models.ForeignKey(Parent, models.CASCADE)
1239
1240 class Meta:
1241 ordering = ("parent__missing_field",)
1242
1243 self.assertEqual(
1244 Child.check(),
1245 [
1246 Error(
1247 "'ordering' refers to the nonexistent field, related field, "
1248 "or lookup 'parent__missing_field'.",
1249 obj=Child,
1250 id="models.E015",
1251 )
1252 ],
1253 )
1254
1255 def test_ordering_pointing_to_non_related_field(self):
1256 class Child(models.Model):
1257 parent = models.IntegerField()
1258
1259 class Meta:
1260 ordering = ("parent__missing_field",)
1261
1262 self.assertEqual(
1263 Child.check(),
1264 [
1265 Error(
1266 "'ordering' refers to the nonexistent field, related field, "
1267 "or lookup 'parent__missing_field'.",
1268 obj=Child,
1269 id="models.E015",
1270 )
1271 ],
1272 )
1273
1274 def test_ordering_pointing_to_two_related_model_field(self):
1275 class Parent2(models.Model):
1276 pass
1277
1278 class Parent1(models.Model):
1279 parent2 = models.ForeignKey(Parent2, models.CASCADE)
1280
1281 class Child(models.Model):
1282 parent1 = models.ForeignKey(Parent1, models.CASCADE)
1283
1284 class Meta:
1285 ordering = ("parent1__parent2__missing_field",)
1286
1287 self.assertEqual(
1288 Child.check(),
1289 [
1290 Error(
1291 "'ordering' refers to the nonexistent field, related field, "
1292 "or lookup 'parent1__parent2__missing_field'.",
1293 obj=Child,
1294 id="models.E015",
1295 )
1296 ],
1297 )
1298
1299 def test_ordering_pointing_multiple_times_to_model_fields(self):
1300 class Parent(models.Model):
1301 field1 = models.CharField(max_length=100)
1302 field2 = models.CharField(max_length=100)
1303
1304 class Child(models.Model):
1305 parent = models.ForeignKey(Parent, models.CASCADE)
1306
1307 class Meta:
1308 ordering = ("parent__field1__field2",)
1309
1310 self.assertEqual(
1311 Child.check(),
1312 [
1313 Error(
1314 "'ordering' refers to the nonexistent field, related field, "
1315 "or lookup 'parent__field1__field2'.",
1316 obj=Child,
1317 id="models.E015",
1318 )
1319 ],
1320 )
1321
1322 def test_ordering_allows_registered_lookups(self):
1323 class Model(models.Model):
1324 test = models.CharField(max_length=100)
1325
1326 class Meta:
1327 ordering = ("test__lower",)
1328
1329 with register_lookup(models.CharField, Lower):
1330 self.assertEqual(Model.check(), [])
1331
1332 def test_ordering_pointing_to_lookup_not_transform(self):
1333 class Model(models.Model):
1334 test = models.CharField(max_length=100)
1335
1336 class Meta:
1337 ordering = ("test__isnull",)
1338
1339 self.assertEqual(Model.check(), [])
1340
1341 def test_ordering_pointing_to_related_model_pk(self):
1342 class Parent(models.Model):
1343 pass
1344
1345 class Child(models.Model):
1346 parent = models.ForeignKey(Parent, models.CASCADE)
1347
1348 class Meta:
1349 ordering = ("parent__pk",)
1350
1351 self.assertEqual(Child.check(), [])
1352
1353 def test_ordering_pointing_to_foreignkey_field(self):
1354 class Parent(models.Model):
1355 pass
1356
1357 class Child(models.Model):
1358 parent = models.ForeignKey(Parent, models.CASCADE)
1359
1360 class Meta:
1361 ordering = ("parent_id",)
1362
1363 self.assertFalse(Child.check())
1364
1365 def test_name_beginning_with_underscore(self):
1366 class _Model(models.Model):
1367 pass
1368
1369 self.assertEqual(
1370 _Model.check(),
1371 [
1372 Error(
1373 "The model name '_Model' cannot start or end with an underscore "
1374 "as it collides with the query lookup syntax.",
1375 obj=_Model,
1376 id="models.E023",
1377 )
1378 ],
1379 )
1380
1381 def test_name_ending_with_underscore(self):
1382 class Model_(models.Model):
1383 pass
1384
1385 self.assertEqual(
1386 Model_.check(),
1387 [
1388 Error(
1389 "The model name 'Model_' cannot start or end with an underscore "
1390 "as it collides with the query lookup syntax.",
1391 obj=Model_,
1392 id="models.E023",
1393 )
1394 ],
1395 )
1396
1397 def test_name_contains_double_underscores(self):
1398 class Test__Model(models.Model):
1399 pass
1400
1401 self.assertEqual(
1402 Test__Model.check(),
1403 [
1404 Error(
1405 "The model name 'Test__Model' cannot contain double underscores "
1406 "as it collides with the query lookup syntax.",
1407 obj=Test__Model,
1408 id="models.E024",
1409 )
1410 ],
1411 )
1412
1413 def test_property_and_related_field_accessor_clash(self):
1414 class Model(models.Model):
1415 fk = models.ForeignKey("self", models.CASCADE)
1416
1417 # Override related field accessor.
1418 Model.fk_id = property(lambda self: "ERROR")
1419
1420 self.assertEqual(
1421 Model.check(),
1422 [
1423 Error(
1424 "The property 'fk_id' clashes with a related field accessor.",
1425 obj=Model,
1426 id="models.E025",
1427 )
1428 ],
1429 )
1430
1431 def test_inherited_overriden_property_no_clash(self):
1432 class Cheese:
1433 @property
1434 def filling_id(self):
1435 pass
1436
1437 class Sandwich(Cheese, models.Model):
1438 filling = models.ForeignKey("self", models.CASCADE)
1439
1440 self.assertEqual(Sandwich.check(), [])
1441
1442 def test_single_primary_key(self):
1443 class Model(models.Model):
1444 foo = models.IntegerField(primary_key=True)
1445 bar = models.IntegerField(primary_key=True)
1446
1447 self.assertEqual(
1448 Model.check(),
1449 [
1450 Error(
1451 "The model cannot have more than one field with "
1452 "'primary_key=True'.",
1453 obj=Model,
1454 id="models.E026",
1455 )
1456 ],
1457 )
1458
1459 @override_settings(TEST_SWAPPED_MODEL_BAD_VALUE="not-a-model")
1460 def test_swappable_missing_app_name(self):
1461 class Model(models.Model):
1462 class Meta:
1463 swappable = "TEST_SWAPPED_MODEL_BAD_VALUE"
1464
1465 self.assertEqual(
1466 Model.check(),
1467 [
1468 Error(
1469 "'TEST_SWAPPED_MODEL_BAD_VALUE' is not of the form "
1470 "'app_label.app_name'.",
1471 id="models.E001",
1472 ),
1473 ],
1474 )
1475
1476 @override_settings(TEST_SWAPPED_MODEL_BAD_MODEL="not_an_app.Target")
1477 def test_swappable_missing_app(self):
1478 class Model(models.Model):
1479 class Meta:
1480 swappable = "TEST_SWAPPED_MODEL_BAD_MODEL"
1481
1482 self.assertEqual(
1483 Model.check(),
1484 [
1485 Error(
1486 "'TEST_SWAPPED_MODEL_BAD_MODEL' references 'not_an_app.Target', "
1487 "which has not been installed, or is abstract.",
1488 id="models.E002",
1489 ),
1490 ],
1491 )
1492
1493 def test_two_m2m_through_same_relationship(self):
1494 class Person(models.Model):
1495 pass
1496
1497 class Group(models.Model):
1498 primary = models.ManyToManyField(
1499 Person, through="Membership", related_name="primary"
1500 )
1501 secondary = models.ManyToManyField(
1502 Person, through="Membership", related_name="secondary"
1503 )
1504
1505 class Membership(models.Model):
1506 person = models.ForeignKey(Person, models.CASCADE)
1507 group = models.ForeignKey(Group, models.CASCADE)
1508
1509 self.assertEqual(
1510 Group.check(),
1511 [
1512 Error(
1513 "The model has two identical many-to-many relations through "
1514 "the intermediate model 'invalid_models_tests.Membership'.",
1515 obj=Group,
1516 id="models.E003",
1517 )
1518 ],
1519 )
1520
1521 def test_two_m2m_through_same_model_with_different_through_fields(self):
1522 class Country(models.Model):
1523 pass
1524
1525 class ShippingMethod(models.Model):
1526 to_countries = models.ManyToManyField(
1527 Country,
1528 through="ShippingMethodPrice",
1529 through_fields=("method", "to_country"),
1530 )
1531 from_countries = models.ManyToManyField(
1532 Country,
1533 through="ShippingMethodPrice",
1534 through_fields=("method", "from_country"),
1535 related_name="+",
1536 )
1537
1538 class ShippingMethodPrice(models.Model):
1539 method = models.ForeignKey(ShippingMethod, models.CASCADE)
1540 to_country = models.ForeignKey(Country, models.CASCADE)
1541 from_country = models.ForeignKey(Country, models.CASCADE)
1542
1543 self.assertEqual(ShippingMethod.check(), [])
1544
1545 def test_onetoone_with_parent_model(self):
1546 class Place(models.Model):
1547 pass
1548
1549 class ParkingLot(Place):
1550 other_place = models.OneToOneField(
1551 Place, models.CASCADE, related_name="other_parking"
1552 )
1553
1554 self.assertEqual(ParkingLot.check(), [])
1555
1556 def test_onetoone_with_explicit_parent_link_parent_model(self):
1557 class Place(models.Model):
1558 pass
1559
1560 class ParkingLot(Place):
1561 place = models.OneToOneField(
1562 Place, models.CASCADE, parent_link=True, primary_key=True
1563 )
1564 other_place = models.OneToOneField(
1565 Place, models.CASCADE, related_name="other_parking"
1566 )
1567
1568 self.assertEqual(ParkingLot.check(), [])
1569
1570 def test_m2m_table_name_clash(self):
1571 class Foo(models.Model):
1572 bar = models.ManyToManyField("Bar", db_table="myapp_bar")
1573
1574 class Meta:
1575 db_table = "myapp_foo"
1576
1577 class Bar(models.Model):
1578 class Meta:
1579 db_table = "myapp_bar"
1580
1581 self.assertEqual(
1582 Foo.check(),
1583 [
1584 Error(
1585 "The field's intermediary table 'myapp_bar' clashes with the "
1586 "table name of 'invalid_models_tests.Bar'.",
1587 obj=Foo._meta.get_field("bar"),
1588 id="fields.E340",
1589 )
1590 ],
1591 )
1592
1593 @override_settings(
1594 DATABASE_ROUTERS=["invalid_models_tests.test_models.EmptyRouter"]
1595 )
1596 def test_m2m_table_name_clash_database_routers_installed(self):
1597 class Foo(models.Model):
1598 bar = models.ManyToManyField("Bar", db_table="myapp_bar")
1599
1600 class Meta:
1601 db_table = "myapp_foo"
1602
1603 class Bar(models.Model):
1604 class Meta:
1605 db_table = "myapp_bar"
1606
1607 self.assertEqual(
1608 Foo.check(),
1609 [
1610 Warning(
1611 "The field's intermediary table 'myapp_bar' clashes with the "
1612 "table name of 'invalid_models_tests.Bar'.",
1613 obj=Foo._meta.get_field("bar"),
1614 hint=(
1615 "You have configured settings.DATABASE_ROUTERS. Verify "
1616 "that the table of 'invalid_models_tests.Bar' is "
1617 "correctly routed to a separate database."
1618 ),
1619 id="fields.W344",
1620 ),
1621 ],
1622 )
1623
1624 def test_m2m_field_table_name_clash(self):
1625 class Foo(models.Model):
1626 pass
1627
1628 class Bar(models.Model):
1629 foos = models.ManyToManyField(Foo, db_table="clash")
1630
1631 class Baz(models.Model):
1632 foos = models.ManyToManyField(Foo, db_table="clash")
1633
1634 self.assertEqual(
1635 Bar.check() + Baz.check(),
1636 [
1637 Error(
1638 "The field's intermediary table 'clash' clashes with the "
1639 "table name of 'invalid_models_tests.Baz.foos'.",
1640 obj=Bar._meta.get_field("foos"),
1641 id="fields.E340",
1642 ),
1643 Error(
1644 "The field's intermediary table 'clash' clashes with the "
1645 "table name of 'invalid_models_tests.Bar.foos'.",
1646 obj=Baz._meta.get_field("foos"),
1647 id="fields.E340",
1648 ),
1649 ],
1650 )
1651
1652 @override_settings(
1653 DATABASE_ROUTERS=["invalid_models_tests.test_models.EmptyRouter"]
1654 )
1655 def test_m2m_field_table_name_clash_database_routers_installed(self):
1656 class Foo(models.Model):
1657 pass
1658
1659 class Bar(models.Model):
1660 foos = models.ManyToManyField(Foo, db_table="clash")
1661
1662 class Baz(models.Model):
1663 foos = models.ManyToManyField(Foo, db_table="clash")
1664
1665 self.assertEqual(
1666 Bar.check() + Baz.check(),
1667 [
1668 Warning(
1669 "The field's intermediary table 'clash' clashes with the "
1670 "table name of 'invalid_models_tests.%s.foos'." % clashing_model,
1671 obj=model_cls._meta.get_field("foos"),
1672 hint=(
1673 "You have configured settings.DATABASE_ROUTERS. Verify "
1674 "that the table of 'invalid_models_tests.%s.foos' is "
1675 "correctly routed to a separate database." % clashing_model
1676 ),
1677 id="fields.W344",
1678 )
1679 for model_cls, clashing_model in [(Bar, "Baz"), (Baz, "Bar")]
1680 ],
1681 )
1682
1683 def test_m2m_autogenerated_table_name_clash(self):
1684 class Foo(models.Model):
1685 class Meta:
1686 db_table = "bar_foos"
1687
1688 class Bar(models.Model):
1689 # The autogenerated `db_table` will be bar_foos.
1690 foos = models.ManyToManyField(Foo)
1691
1692 class Meta:
1693 db_table = "bar"
1694
1695 self.assertEqual(
1696 Bar.check(),
1697 [
1698 Error(
1699 "The field's intermediary table 'bar_foos' clashes with the "
1700 "table name of 'invalid_models_tests.Foo'.",
1701 obj=Bar._meta.get_field("foos"),
1702 id="fields.E340",
1703 )
1704 ],
1705 )
1706
1707 @override_settings(
1708 DATABASE_ROUTERS=["invalid_models_tests.test_models.EmptyRouter"]
1709 )
1710 def test_m2m_autogenerated_table_name_clash_database_routers_installed(self):
1711 class Foo(models.Model):
1712 class Meta:
1713 db_table = "bar_foos"
1714
1715 class Bar(models.Model):
1716 # The autogenerated db_table is bar_foos.
1717 foos = models.ManyToManyField(Foo)
1718
1719 class Meta:
1720 db_table = "bar"
1721
1722 self.assertEqual(
1723 Bar.check(),
1724 [
1725 Warning(
1726 "The field's intermediary table 'bar_foos' clashes with the "
1727 "table name of 'invalid_models_tests.Foo'.",
1728 obj=Bar._meta.get_field("foos"),
1729 hint=(
1730 "You have configured settings.DATABASE_ROUTERS. Verify "
1731 "that the table of 'invalid_models_tests.Foo' is "
1732 "correctly routed to a separate database."
1733 ),
1734 id="fields.W344",
1735 ),
1736 ],
1737 )
1738
1739 def test_m2m_unmanaged_shadow_models_not_checked(self):
1740 class A1(models.Model):
1741 pass
1742
1743 class C1(models.Model):
1744 mm_a = models.ManyToManyField(A1, db_table="d1")
1745
1746 # Unmanaged models that shadow the above models. Reused table names
1747 # shouldn't be flagged by any checks.
1748 class A2(models.Model):
1749 class Meta:
1750 managed = False
1751
1752 class C2(models.Model):
1753 mm_a = models.ManyToManyField(A2, through="Intermediate")
1754
1755 class Meta:
1756 managed = False
1757
1758 class Intermediate(models.Model):
1759 a2 = models.ForeignKey(A2, models.CASCADE, db_column="a1_id")
1760 c2 = models.ForeignKey(C2, models.CASCADE, db_column="c1_id")
1761
1762 class Meta:
1763 db_table = "d1"
1764 managed = False
1765
1766 self.assertEqual(C1.check(), [])
1767 self.assertEqual(C2.check(), [])
1768
1769 def test_m2m_to_concrete_and_proxy_allowed(self):
1770 class A(models.Model):
1771 pass
1772
1773 class Through(models.Model):
1774 a = models.ForeignKey("A", models.CASCADE)
1775 c = models.ForeignKey("C", models.CASCADE)
1776
1777 class ThroughProxy(Through):
1778 class Meta:
1779 proxy = True
1780
1781 class C(models.Model):
1782 mm_a = models.ManyToManyField(A, through=Through)
1783 mm_aproxy = models.ManyToManyField(
1784 A, through=ThroughProxy, related_name="proxied_m2m"
1785 )
1786
1787 self.assertEqual(C.check(), [])
1788
1789 @isolate_apps("django.contrib.auth", kwarg_name="apps")
1790 def test_lazy_reference_checks(self, apps):
1791 class DummyModel(models.Model):
1792 author = models.ForeignKey("Author", models.CASCADE)
1793
1794 class Meta:
1795 app_label = "invalid_models_tests"
1796
1797 class DummyClass:
1798 def __call__(self, **kwargs):
1799 pass
1800
1801 def dummy_method(self):
1802 pass
1803
1804 def dummy_function(*args, **kwargs):
1805 pass
1806
1807 apps.lazy_model_operation(dummy_function, ("auth", "imaginarymodel"))
1808 apps.lazy_model_operation(dummy_function, ("fanciful_app", "imaginarymodel"))
1809
1810 post_init.connect(dummy_function, sender="missing-app.Model", apps=apps)
1811 post_init.connect(DummyClass(), sender="missing-app.Model", apps=apps)
1812 post_init.connect(
1813 DummyClass().dummy_method, sender="missing-app.Model", apps=apps
1814 )
1815
1816 self.assertEqual(
1817 _check_lazy_references(apps),
1818 [
1819 Error(
1820 "%r contains a lazy reference to auth.imaginarymodel, "
1821 "but app 'auth' doesn't provide model 'imaginarymodel'."
1822 % dummy_function,
1823 obj=dummy_function,
1824 id="models.E022",
1825 ),
1826 Error(
1827 "%r contains a lazy reference to fanciful_app.imaginarymodel, "
1828 "but app 'fanciful_app' isn't installed." % dummy_function,
1829 obj=dummy_function,
1830 id="models.E022",
1831 ),
1832 Error(
1833 "An instance of class 'DummyClass' was connected to "
1834 "the 'post_init' signal with a lazy reference to the sender "
1835 "'missing-app.model', but app 'missing-app' isn't installed.",
1836 hint=None,
1837 obj="invalid_models_tests.test_models",
1838 id="signals.E001",
1839 ),
1840 Error(
1841 "Bound method 'DummyClass.dummy_method' was connected to the "
1842 "'post_init' signal with a lazy reference to the sender "
1843 "'missing-app.model', but app 'missing-app' isn't installed.",
1844 hint=None,
1845 obj="invalid_models_tests.test_models",
1846 id="signals.E001",
1847 ),
1848 Error(
1849 "The field invalid_models_tests.DummyModel.author was declared "
1850 "with a lazy reference to 'invalid_models_tests.author', but app "
1851 "'invalid_models_tests' isn't installed.",
1852 hint=None,
1853 obj=DummyModel.author.field,
1854 id="fields.E307",
1855 ),
1856 Error(
1857 "The function 'dummy_function' was connected to the 'post_init' "
1858 "signal with a lazy reference to the sender "
1859 "'missing-app.model', but app 'missing-app' isn't installed.",
1860 hint=None,
1861 obj="invalid_models_tests.test_models",
1862 id="signals.E001",
1863 ),
1864 ],
1865 )
1866
1867
1868 @isolate_apps("invalid_models_tests")
1869 class DbTableCommentTests(TestCase):
1870 def test_db_table_comment(self):
1871 class Model(models.Model):
1872 class Meta:
1873 db_table_comment = "Table comment"
1874
1875 errors = Model.check(databases=self.databases)
1876 expected = (
1877 []
1878 if connection.features.supports_comments
1879 else [
1880 Warning(
1881 f"{connection.display_name} does not support comments on tables "
1882 f"(db_table_comment).",
1883 obj=Model,
1884 id="models.W046",
1885 ),
1886 ]
1887 )
1888 self.assertEqual(errors, expected)
1889
1890 def test_db_table_comment_required_db_features(self):
1891 class Model(models.Model):
1892 class Meta:
1893 db_table_comment = "Table comment"
1894 required_db_features = {"supports_comments"}
1895
1896 self.assertEqual(Model.check(databases=self.databases), [])
1897
1898
1899 class MultipleAutoFieldsTests(TestCase):
1900 def test_multiple_autofields(self):
1901 msg = (
1902 "Model invalid_models_tests.MultipleAutoFields can't have more "
1903 "than one auto-generated field."
1904 )
1905 with self.assertRaisesMessage(ValueError, msg):
1906
1907 class MultipleAutoFields(models.Model):
1908 auto1 = models.AutoField(primary_key=True)
1909 auto2 = models.AutoField(primary_key=True)
1910
1911
1912 @isolate_apps("invalid_models_tests")
1913 class JSONFieldTests(TestCase):
1914 @skipUnlessDBFeature("supports_json_field")
1915 def test_ordering_pointing_to_json_field_value(self):
1916 class Model(models.Model):
1917 field = models.JSONField()
1918
1919 class Meta:
1920 ordering = ["field__value"]
1921
1922 self.assertEqual(Model.check(databases=self.databases), [])
1923
1924 def test_check_jsonfield(self):
1925 class Model(models.Model):
1926 field = models.JSONField()
1927
1928 error = Error(
1929 "%s does not support JSONFields." % connection.display_name,
1930 obj=Model,
1931 id="fields.E180",
1932 )
1933 expected = [] if connection.features.supports_json_field else [error]
1934 self.assertEqual(Model.check(databases=self.databases), expected)
1935
1936 def test_check_jsonfield_required_db_features(self):
1937 class Model(models.Model):
1938 field = models.JSONField()
1939
1940 class Meta:
1941 required_db_features = {"supports_json_field"}
1942
1943 self.assertEqual(Model.check(databases=self.databases), [])
1944
1945
1946 @isolate_apps("invalid_models_tests")
1947 class ConstraintsTests(TestCase):
1948 def test_check_constraints(self):
1949 class Model(models.Model):
1950 age = models.IntegerField()
1951
1952 class Meta:
1953 constraints = [
1954 models.CheckConstraint(
1955 condition=models.Q(age__gte=18), name="is_adult"
1956 )
1957 ]
1958
1959 errors = Model.check(databases=self.databases)
1960 warn = Warning(
1961 "%s does not support check constraints." % connection.display_name,
1962 hint=(
1963 "A constraint won't be created. Silence this warning if you "
1964 "don't care about it."
1965 ),
1966 obj=Model,
1967 id="models.W027",
1968 )
1969 expected = (
1970 [] if connection.features.supports_table_check_constraints else [warn]
1971 )
1972 self.assertCountEqual(errors, expected)
1973
1974 def test_check_constraints_required_db_features(self):
1975 class Model(models.Model):
1976 age = models.IntegerField()
1977
1978 class Meta:
1979 required_db_features = {"supports_table_check_constraints"}
1980 constraints = [
1981 models.CheckConstraint(
1982 condition=models.Q(age__gte=18), name="is_adult"
1983 )
1984 ]
1985
1986 self.assertEqual(Model.check(databases=self.databases), [])
1987
1988 def test_check_constraint_pointing_to_missing_field(self):
1989 class Model(models.Model):
1990 class Meta:
1991 required_db_features = {"supports_table_check_constraints"}
1992 constraints = [
1993 models.CheckConstraint(
1994 name="name",
1995 condition=models.Q(missing_field=2),
1996 ),
1997 ]
1998
1999 self.assertEqual(
2000 Model.check(databases=self.databases),
2001 (
2002 [
2003 Error(
2004 "'constraints' refers to the nonexistent field "
2005 "'missing_field'.",
2006 obj=Model,
2007 id="models.E012",
2008 ),
2009 ]
2010 if connection.features.supports_table_check_constraints
2011 else []
2012 ),
2013 )
2014
2015 @skipUnlessDBFeature("supports_table_check_constraints")
2016 def test_check_constraint_pointing_to_reverse_fk(self):
2017 class Model(models.Model):
2018 parent = models.ForeignKey("self", models.CASCADE, related_name="parents")
2019
2020 class Meta:
2021 constraints = [
2022 models.CheckConstraint(name="name", condition=models.Q(parents=3)),
2023 ]
2024
2025 self.assertEqual(
2026 Model.check(databases=self.databases),
2027 [
2028 Error(
2029 "'constraints' refers to the nonexistent field 'parents'.",
2030 obj=Model,
2031 id="models.E012",
2032 ),
2033 ],
2034 )
2035
2036 @skipUnlessDBFeature("supports_table_check_constraints")
2037 def test_check_constraint_pointing_to_reverse_o2o(self):
2038 class Model(models.Model):
2039 parent = models.OneToOneField("self", models.CASCADE)
2040
2041 class Meta:
2042 constraints = [
2043 models.CheckConstraint(
2044 name="name",
2045 condition=models.Q(model__isnull=True),
2046 ),
2047 ]
2048
2049 self.assertEqual(
2050 Model.check(databases=self.databases),
2051 [
2052 Error(
2053 "'constraints' refers to the nonexistent field 'model'.",
2054 obj=Model,
2055 id="models.E012",
2056 ),
2057 ],
2058 )
2059
2060 @skipUnlessDBFeature("supports_table_check_constraints")
2061 def test_check_constraint_pointing_to_m2m_field(self):
2062 class Model(models.Model):
2063 m2m = models.ManyToManyField("self")
2064
2065 class Meta:
2066 constraints = [
2067 models.CheckConstraint(name="name", condition=models.Q(m2m=2)),
2068 ]
2069
2070 self.assertEqual(
2071 Model.check(databases=self.databases),
2072 [
2073 Error(
2074 "'constraints' refers to a ManyToManyField 'm2m', but "
2075 "ManyToManyFields are not permitted in 'constraints'.",
2076 obj=Model,
2077 id="models.E013",
2078 ),
2079 ],
2080 )
2081
2082 @skipUnlessDBFeature("supports_table_check_constraints")
2083 def test_check_constraint_pointing_to_fk(self):
2084 class Target(models.Model):
2085 pass
2086
2087 class Model(models.Model):
2088 fk_1 = models.ForeignKey(Target, models.CASCADE, related_name="target_1")
2089 fk_2 = models.ForeignKey(Target, models.CASCADE, related_name="target_2")
2090
2091 class Meta:
2092 constraints = [
2093 models.CheckConstraint(
2094 name="name",
2095 condition=models.Q(fk_1_id=2) | models.Q(fk_2=2),
2096 ),
2097 ]
2098
2099 self.assertEqual(Model.check(databases=self.databases), [])
2100
2101 @skipUnlessDBFeature("supports_table_check_constraints")
2102 def test_check_constraint_pointing_to_pk(self):
2103 class Model(models.Model):
2104 age = models.SmallIntegerField()
2105
2106 class Meta:
2107 constraints = [
2108 models.CheckConstraint(
2109 name="name",
2110 condition=models.Q(pk__gt=5) & models.Q(age__gt=models.F("pk")),
2111 ),
2112 ]
2113
2114 self.assertEqual(Model.check(databases=self.databases), [])
2115
2116 @skipUnlessDBFeature("supports_table_check_constraints")
2117 def test_check_constraint_pointing_to_non_local_field(self):
2118 class Parent(models.Model):
2119 field1 = models.IntegerField()
2120
2121 class Child(Parent):
2122 pass
2123
2124 class Meta:
2125 constraints = [
2126 models.CheckConstraint(name="name", condition=models.Q(field1=1)),
2127 ]
2128
2129 self.assertEqual(
2130 Child.check(databases=self.databases),
2131 [
2132 Error(
2133 "'constraints' refers to field 'field1' which is not local to "
2134 "model 'Child'.",
2135 hint="This issue may be caused by multi-table inheritance.",
2136 obj=Child,
2137 id="models.E016",
2138 ),
2139 ],
2140 )
2141
2142 @skipUnlessDBFeature("supports_table_check_constraints")
2143 def test_check_constraint_pointing_to_joined_fields(self):
2144 class Model(models.Model):
2145 name = models.CharField(max_length=10)
2146 field1 = models.PositiveSmallIntegerField()
2147 field2 = models.PositiveSmallIntegerField()
2148 field3 = models.PositiveSmallIntegerField()
2149 parent = models.ForeignKey("self", models.CASCADE)
2150 previous = models.OneToOneField("self", models.CASCADE, related_name="next")
2151
2152 class Meta:
2153 constraints = [
2154 models.CheckConstraint(
2155 name="name1",
2156 condition=models.Q(
2157 field1__lt=models.F("parent__field1")
2158 + models.F("parent__field2")
2159 ),
2160 ),
2161 models.CheckConstraint(
2162 name="name2", condition=models.Q(name=Lower("parent__name"))
2163 ),
2164 models.CheckConstraint(
2165 name="name3",
2166 condition=models.Q(parent__field3=models.F("field1")),
2167 ),
2168 models.CheckConstraint(
2169 name="name4",
2170 condition=models.Q(name=Lower("previous__name")),
2171 ),
2172 ]
2173
2174 joined_fields = [
2175 "parent__field1",
2176 "parent__field2",
2177 "parent__field3",
2178 "parent__name",
2179 "previous__name",
2180 ]
2181 errors = Model.check(databases=self.databases)
2182 expected_errors = [
2183 Error(
2184 "'constraints' refers to the joined field '%s'." % field_name,
2185 obj=Model,
2186 id="models.E041",
2187 )
2188 for field_name in joined_fields
2189 ]
2190 self.assertCountEqual(errors, expected_errors)
2191
2192 @skipUnlessDBFeature("supports_table_check_constraints")
2193 def test_check_constraint_pointing_to_joined_fields_complex_check(self):
2194 class Model(models.Model):
2195 name = models.PositiveSmallIntegerField()
2196 field1 = models.PositiveSmallIntegerField()
2197 field2 = models.PositiveSmallIntegerField()
2198 parent = models.ForeignKey("self", models.CASCADE)
2199
2200 class Meta:
2201 constraints = [
2202 models.CheckConstraint(
2203 name="name",
2204 condition=models.Q(
2205 (
2206 models.Q(name="test")
2207 & models.Q(field1__lt=models.F("parent__field1"))
2208 )
2209 | (
2210 models.Q(name__startswith=Lower("parent__name"))
2211 & models.Q(
2212 field1__gte=(
2213 models.F("parent__field1")
2214 + models.F("parent__field2")
2215 )
2216 )
2217 )
2218 )
2219 | (models.Q(name="test1")),
2220 ),
2221 ]
2222
2223 joined_fields = ["parent__field1", "parent__field2", "parent__name"]
2224 errors = Model.check(databases=self.databases)
2225 expected_errors = [
2226 Error(
2227 "'constraints' refers to the joined field '%s'." % field_name,
2228 obj=Model,
2229 id="models.E041",
2230 )
2231 for field_name in joined_fields
2232 ]
2233 self.assertCountEqual(errors, expected_errors)
2234
2235 def test_check_constraint_raw_sql_check(self):
2236 class Model(models.Model):
2237 class Meta:
2238 required_db_features = {"supports_table_check_constraints"}
2239 constraints = [
2240 models.CheckConstraint(
2241 condition=models.Q(id__gt=0), name="q_check"
2242 ),
2243 models.CheckConstraint(
2244 condition=models.ExpressionWrapper(
2245 models.Q(price__gt=20),
2246 output_field=models.BooleanField(),
2247 ),
2248 name="expression_wrapper_check",
2249 ),
2250 models.CheckConstraint(
2251 condition=models.expressions.RawSQL(
2252 "id = 0",
2253 params=(),
2254 output_field=models.BooleanField(),
2255 ),
2256 name="raw_sql_check",
2257 ),
2258 models.CheckConstraint(
2259 condition=models.Q(
2260 models.ExpressionWrapper(
2261 models.Q(
2262 models.expressions.RawSQL(
2263 "id = 0",
2264 params=(),
2265 output_field=models.BooleanField(),
2266 )
2267 ),
2268 output_field=models.BooleanField(),
2269 )
2270 ),
2271 name="nested_raw_sql_check",
2272 ),
2273 ]
2274
2275 expected_warnings = (
2276 [
2277 Warning(
2278 "Check constraint 'raw_sql_check' contains RawSQL() expression and "
2279 "won't be validated during the model full_clean().",
2280 hint="Silence this warning if you don't care about it.",
2281 obj=Model,
2282 id="models.W045",
2283 ),
2284 Warning(
2285 "Check constraint 'nested_raw_sql_check' contains RawSQL() "
2286 "expression and won't be validated during the model full_clean().",
2287 hint="Silence this warning if you don't care about it.",
2288 obj=Model,
2289 id="models.W045",
2290 ),
2291 ]
2292 if connection.features.supports_table_check_constraints
2293 else []
2294 )
2295 self.assertEqual(Model.check(databases=self.databases), expected_warnings)
2296
2297 @skipUnlessDBFeature("supports_table_check_constraints")
2298 def test_check_constraint_pointing_to_composite_primary_key(self):
2299 class Model(models.Model):
2300 pk = models.CompositePrimaryKey("version", "name")
2301 version = models.IntegerField()
2302 name = models.CharField(max_length=20)
2303
2304 class Meta:
2305 constraints = [
2306 models.CheckConstraint(
2307 name="name",
2308 condition=models.Q(pk__gt=(7, "focal")),
2309 ),
2310 ]
2311
2312 self.assertEqual(
2313 Model.check(databases=self.databases),
2314 [
2315 Error(
2316 "'constraints' refers to a CompositePrimaryKey 'pk', but "
2317 "CompositePrimaryKeys are not permitted in 'constraints'.",
2318 obj=Model,
2319 id="models.E048",
2320 ),
2321 ],
2322 )
2323
2324 def test_unique_constraint_with_condition(self):
2325 class Model(models.Model):
2326 age = models.IntegerField()
2327
2328 class Meta:
2329 constraints = [
2330 models.UniqueConstraint(
2331 fields=["age"],
2332 name="unique_age_gte_100",
2333 condition=models.Q(age__gte=100),
2334 ),
2335 ]
2336
2337 errors = Model.check(databases=self.databases)
2338 expected = (
2339 []
2340 if connection.features.supports_partial_indexes
2341 else [
2342 Warning(
2343 "%s does not support unique constraints with conditions."
2344 % connection.display_name,
2345 hint=(
2346 "A constraint won't be created. Silence this warning if "
2347 "you don't care about it."
2348 ),
2349 obj=Model,
2350 id="models.W036",
2351 ),
2352 ]
2353 )
2354 self.assertEqual(errors, expected)
2355
2356 def test_unique_constraint_with_condition_required_db_features(self):
2357 class Model(models.Model):
2358 age = models.IntegerField()
2359
2360 class Meta:
2361 required_db_features = {"supports_partial_indexes"}
2362 constraints = [
2363 models.UniqueConstraint(
2364 fields=["age"],
2365 name="unique_age_gte_100",
2366 condition=models.Q(age__gte=100),
2367 ),
2368 ]
2369
2370 self.assertEqual(Model.check(databases=self.databases), [])
2371
2372 def test_unique_constraint_condition_pointing_to_missing_field(self):
2373 class Model(models.Model):
2374 age = models.SmallIntegerField()
2375
2376 class Meta:
2377 required_db_features = {"supports_partial_indexes"}
2378 constraints = [
2379 models.UniqueConstraint(
2380 name="name",
2381 fields=["age"],
2382 condition=models.Q(missing_field=2),
2383 ),
2384 ]
2385
2386 self.assertEqual(
2387 Model.check(databases=self.databases),
2388 (
2389 [
2390 Error(
2391 "'constraints' refers to the nonexistent field "
2392 "'missing_field'.",
2393 obj=Model,
2394 id="models.E012",
2395 ),
2396 ]
2397 if connection.features.supports_partial_indexes
2398 else []
2399 ),
2400 )
2401
2402 def test_unique_constraint_condition_pointing_to_joined_fields(self):
2403 class Model(models.Model):
2404 age = models.SmallIntegerField()
2405 parent = models.ForeignKey("self", models.CASCADE)
2406
2407 class Meta:
2408 required_db_features = {"supports_partial_indexes"}
2409 constraints = [
2410 models.UniqueConstraint(
2411 name="name",
2412 fields=["age"],
2413 condition=models.Q(parent__age__lt=2),
2414 ),
2415 ]
2416
2417 self.assertEqual(
2418 Model.check(databases=self.databases),
2419 (
2420 [
2421 Error(
2422 "'constraints' refers to the joined field 'parent__age__lt'.",
2423 obj=Model,
2424 id="models.E041",
2425 )
2426 ]
2427 if connection.features.supports_partial_indexes
2428 else []
2429 ),
2430 )
2431
2432 def test_unique_constraint_pointing_to_reverse_o2o(self):
2433 class Model(models.Model):
2434 parent = models.OneToOneField("self", models.CASCADE)
2435
2436 class Meta:
2437 required_db_features = {"supports_partial_indexes"}
2438 constraints = [
2439 models.UniqueConstraint(
2440 fields=["parent"],
2441 name="name",
2442 condition=models.Q(model__isnull=True),
2443 ),
2444 ]
2445
2446 self.assertEqual(
2447 Model.check(databases=self.databases),
2448 (
2449 [
2450 Error(
2451 "'constraints' refers to the nonexistent field 'model'.",
2452 obj=Model,
2453 id="models.E012",
2454 ),
2455 ]
2456 if connection.features.supports_partial_indexes
2457 else []
2458 ),
2459 )
2460
2461 def test_deferrable_unique_constraint(self):
2462 class Model(models.Model):
2463 age = models.IntegerField()
2464
2465 class Meta:
2466 constraints = [
2467 models.UniqueConstraint(
2468 fields=["age"],
2469 name="unique_age_deferrable",
2470 deferrable=models.Deferrable.DEFERRED,
2471 ),
2472 ]
2473
2474 errors = Model.check(databases=self.databases)
2475 expected = (
2476 []
2477 if connection.features.supports_deferrable_unique_constraints
2478 else [
2479 Warning(
2480 "%s does not support deferrable unique constraints."
2481 % connection.display_name,
2482 hint=(
2483 "A constraint won't be created. Silence this warning if "
2484 "you don't care about it."
2485 ),
2486 obj=Model,
2487 id="models.W038",
2488 ),
2489 ]
2490 )
2491 self.assertEqual(errors, expected)
2492
2493 def test_deferrable_unique_constraint_required_db_features(self):
2494 class Model(models.Model):
2495 age = models.IntegerField()
2496
2497 class Meta:
2498 required_db_features = {"supports_deferrable_unique_constraints"}
2499 constraints = [
2500 models.UniqueConstraint(
2501 fields=["age"],
2502 name="unique_age_deferrable",
2503 deferrable=models.Deferrable.IMMEDIATE,
2504 ),
2505 ]
2506
2507 self.assertEqual(Model.check(databases=self.databases), [])
2508
2509 def test_unique_constraint_pointing_to_missing_field(self):
2510 class Model(models.Model):
2511 class Meta:
2512 constraints = [
2513 models.UniqueConstraint(fields=["missing_field"], name="name")
2514 ]
2515
2516 self.assertEqual(
2517 Model.check(databases=self.databases),
2518 [
2519 Error(
2520 "'constraints' refers to the nonexistent field 'missing_field'.",
2521 obj=Model,
2522 id="models.E012",
2523 ),
2524 ],
2525 )
2526
2527 def test_unique_constraint_pointing_to_m2m_field(self):
2528 class Model(models.Model):
2529 m2m = models.ManyToManyField("self")
2530
2531 class Meta:
2532 constraints = [models.UniqueConstraint(fields=["m2m"], name="name")]
2533
2534 self.assertEqual(
2535 Model.check(databases=self.databases),
2536 [
2537 Error(
2538 "'constraints' refers to a ManyToManyField 'm2m', but "
2539 "ManyToManyFields are not permitted in 'constraints'.",
2540 obj=Model,
2541 id="models.E013",
2542 ),
2543 ],
2544 )
2545
2546 def test_unique_constraint_pointing_to_non_local_field(self):
2547 class Parent(models.Model):
2548 field1 = models.IntegerField()
2549
2550 class Child(Parent):
2551 field2 = models.IntegerField()
2552
2553 class Meta:
2554 constraints = [
2555 models.UniqueConstraint(fields=["field2", "field1"], name="name"),
2556 ]
2557
2558 self.assertEqual(
2559 Child.check(databases=self.databases),
2560 [
2561 Error(
2562 "'constraints' refers to field 'field1' which is not local to "
2563 "model 'Child'.",
2564 hint="This issue may be caused by multi-table inheritance.",
2565 obj=Child,
2566 id="models.E016",
2567 ),
2568 ],
2569 )
2570
2571 def test_unique_constraint_pointing_to_fk(self):
2572 class Target(models.Model):
2573 pass
2574
2575 class Model(models.Model):
2576 fk_1 = models.ForeignKey(Target, models.CASCADE, related_name="target_1")
2577 fk_2 = models.ForeignKey(Target, models.CASCADE, related_name="target_2")
2578
2579 class Meta:
2580 constraints = [
2581 models.UniqueConstraint(fields=["fk_1_id", "fk_2"], name="name"),
2582 ]
2583
2584 self.assertEqual(Model.check(databases=self.databases), [])
2585
2586 def test_unique_constraint_pointing_to_composite_primary_key(self):
2587 class Model(models.Model):
2588 pk = models.CompositePrimaryKey("version", "name")
2589 version = models.IntegerField()
2590 name = models.CharField(max_length=20)
2591
2592 class Meta:
2593 constraints = [models.UniqueConstraint(fields=["pk"], name="name")]
2594
2595 self.assertEqual(
2596 Model.check(databases=self.databases),
2597 [
2598 Error(
2599 "'constraints' refers to a CompositePrimaryKey 'pk', but "
2600 "CompositePrimaryKeys are not permitted in 'constraints'.",
2601 obj=Model,
2602 id="models.E048",
2603 ),
2604 ],
2605 )
2606
2607 def test_unique_constraint_with_include(self):
2608 class Model(models.Model):
2609 age = models.IntegerField()
2610
2611 class Meta:
2612 constraints = [
2613 models.UniqueConstraint(
2614 fields=["age"],
2615 name="unique_age_include_id",
2616 include=["id"],
2617 ),
2618 ]
2619
2620 errors = Model.check(databases=self.databases)
2621 expected = (
2622 []
2623 if connection.features.supports_covering_indexes
2624 else [
2625 Warning(
2626 "%s does not support unique constraints with non-key columns."
2627 % connection.display_name,
2628 hint=(
2629 "A constraint won't be created. Silence this warning if "
2630 "you don't care about it."
2631 ),
2632 obj=Model,
2633 id="models.W039",
2634 ),
2635 ]
2636 )
2637 self.assertEqual(errors, expected)
2638
2639 def test_unique_constraint_with_include_required_db_features(self):
2640 class Model(models.Model):
2641 age = models.IntegerField()
2642
2643 class Meta:
2644 required_db_features = {"supports_covering_indexes"}
2645 constraints = [
2646 models.UniqueConstraint(
2647 fields=["age"],
2648 name="unique_age_include_id",
2649 include=["id"],
2650 ),
2651 ]
2652
2653 self.assertEqual(Model.check(databases=self.databases), [])
2654
2655 @skipUnlessDBFeature("supports_covering_indexes")
2656 def test_unique_constraint_include_pointing_to_missing_field(self):
2657 class Model(models.Model):
2658 class Meta:
2659 constraints = [
2660 models.UniqueConstraint(
2661 fields=["id"],
2662 include=["missing_field"],
2663 name="name",
2664 ),
2665 ]
2666
2667 self.assertEqual(
2668 Model.check(databases=self.databases),
2669 [
2670 Error(
2671 "'constraints' refers to the nonexistent field 'missing_field'.",
2672 obj=Model,
2673 id="models.E012",
2674 ),
2675 ],
2676 )
2677
2678 @skipUnlessDBFeature("supports_covering_indexes")
2679 def test_unique_constraint_include_pointing_to_m2m_field(self):
2680 class Model(models.Model):
2681 m2m = models.ManyToManyField("self")
2682
2683 class Meta:
2684 constraints = [
2685 models.UniqueConstraint(
2686 fields=["id"],
2687 include=["m2m"],
2688 name="name",
2689 ),
2690 ]
2691
2692 self.assertEqual(
2693 Model.check(databases=self.databases),
2694 [
2695 Error(
2696 "'constraints' refers to a ManyToManyField 'm2m', but "
2697 "ManyToManyFields are not permitted in 'constraints'.",
2698 obj=Model,
2699 id="models.E013",
2700 ),
2701 ],
2702 )
2703
2704 @skipUnlessDBFeature("supports_covering_indexes")
2705 def test_unique_constraint_include_pointing_to_non_local_field(self):
2706 class Parent(models.Model):
2707 field1 = models.IntegerField()
2708
2709 class Child(Parent):
2710 field2 = models.IntegerField()
2711
2712 class Meta:
2713 constraints = [
2714 models.UniqueConstraint(
2715 fields=["field2"],
2716 include=["field1"],
2717 name="name",
2718 ),
2719 ]
2720
2721 self.assertEqual(
2722 Child.check(databases=self.databases),
2723 [
2724 Error(
2725 "'constraints' refers to field 'field1' which is not local to "
2726 "model 'Child'.",
2727 hint="This issue may be caused by multi-table inheritance.",
2728 obj=Child,
2729 id="models.E016",
2730 ),
2731 ],
2732 )
2733
2734 @skipUnlessDBFeature("supports_covering_indexes")
2735 def test_unique_constraint_include_pointing_to_fk(self):
2736 class Target(models.Model):
2737 pass
2738
2739 class Model(models.Model):
2740 fk_1 = models.ForeignKey(Target, models.CASCADE, related_name="target_1")
2741 fk_2 = models.ForeignKey(Target, models.CASCADE, related_name="target_2")
2742
2743 class Meta:
2744 constraints = [
2745 models.UniqueConstraint(
2746 fields=["id"],
2747 include=["fk_1_id", "fk_2"],
2748 name="name",
2749 ),
2750 ]
2751
2752 self.assertEqual(Model.check(databases=self.databases), [])
2753
2754 @skipUnlessDBFeature("supports_covering_indexes")
2755 def test_unique_constraint_include_pointing_to_composite_primary_key(self):
2756 class Model(models.Model):
2757 pk = models.CompositePrimaryKey("version", "name")
2758 version = models.IntegerField()
2759 name = models.CharField(max_length=20)
2760
2761 class Meta:
2762 constraints = [
2763 models.UniqueConstraint(
2764 fields=["version"],
2765 include=["pk"],
2766 name="name",
2767 ),
2768 ]
2769
2770 self.assertEqual(
2771 Model.check(databases=self.databases),
2772 [
2773 Error(
2774 "'constraints' refers to a CompositePrimaryKey 'pk', but "
2775 "CompositePrimaryKeys are not permitted in 'constraints'.",
2776 obj=Model,
2777 id="models.E048",
2778 ),
2779 ],
2780 )
2781
2782 def test_func_unique_constraint(self):
2783 class Model(models.Model):
2784 name = models.CharField(max_length=10)
2785
2786 class Meta:
2787 constraints = [
2788 models.UniqueConstraint(Lower("name"), name="lower_name_uq"),
2789 ]
2790
2791 warn = Warning(
2792 "%s does not support unique constraints on expressions."
2793 % connection.display_name,
2794 hint=(
2795 "A constraint won't be created. Silence this warning if you "
2796 "don't care about it."
2797 ),
2798 obj=Model,
2799 id="models.W044",
2800 )
2801 expected = [] if connection.features.supports_expression_indexes else [warn]
2802 self.assertEqual(Model.check(databases=self.databases), expected)
2803
2804 def test_func_unique_constraint_required_db_features(self):
2805 class Model(models.Model):
2806 name = models.CharField(max_length=10)
2807
2808 class Meta:
2809 constraints = [
2810 models.UniqueConstraint(Lower("name"), name="lower_name_unq"),
2811 ]
2812 required_db_features = {"supports_expression_indexes"}
2813
2814 self.assertEqual(Model.check(databases=self.databases), [])
2815
2816 def test_unique_constraint_nulls_distinct(self):
2817 class Model(models.Model):
2818 name = models.CharField(max_length=10)
2819
2820 class Meta:
2821 constraints = [
2822 models.UniqueConstraint(
2823 fields=["name"],
2824 name="name_uq_distinct_null",
2825 nulls_distinct=True,
2826 ),
2827 ]
2828
2829 warn = Warning(
2830 f"{connection.display_name} does not support unique constraints with nulls "
2831 "distinct.",
2832 hint=(
2833 "A constraint won't be created. Silence this warning if you don't care "
2834 "about it."
2835 ),
2836 obj=Model,
2837 id="models.W047",
2838 )
2839 expected = (
2840 []
2841 if connection.features.supports_nulls_distinct_unique_constraints
2842 else [warn]
2843 )
2844 self.assertEqual(Model.check(databases=self.databases), expected)
2845
2846 def test_unique_constraint_nulls_distinct_required_db_features(self):
2847 class Model(models.Model):
2848 name = models.CharField(max_length=10)
2849
2850 class Meta:
2851 constraints = [
2852 models.UniqueConstraint(
2853 fields=["name"],
2854 name="name_uq_distinct_null",
2855 nulls_distinct=True,
2856 ),
2857 ]
2858 required_db_features = {"supports_nulls_distinct_unique_constraints"}
2859
2860 self.assertEqual(Model.check(databases=self.databases), [])
2861
2862 @skipUnlessDBFeature("supports_expression_indexes")
2863 def test_func_unique_constraint_expression_custom_lookup(self):
2864 class Model(models.Model):
2865 height = models.IntegerField()
2866 weight = models.IntegerField()
2867
2868 class Meta:
2869 constraints = [
2870 models.UniqueConstraint(
2871 models.F("height")
2872 / (models.F("weight__abs") + models.Value(5)),
2873 name="name",
2874 ),
2875 ]
2876
2877 with register_lookup(models.IntegerField, Abs):
2878 self.assertEqual(Model.check(databases=self.databases), [])
2879
2880 @skipUnlessDBFeature("supports_expression_indexes")
2881 def test_func_unique_constraint_pointing_to_missing_field(self):
2882 class Model(models.Model):
2883 class Meta:
2884 constraints = [
2885 models.UniqueConstraint(Lower("missing_field").desc(), name="name"),
2886 ]
2887
2888 self.assertEqual(
2889 Model.check(databases=self.databases),
2890 [
2891 Error(
2892 "'constraints' refers to the nonexistent field 'missing_field'.",
2893 obj=Model,
2894 id="models.E012",
2895 ),
2896 ],
2897 )
2898
2899 @skipUnlessDBFeature("supports_expression_indexes")
2900 def test_func_unique_constraint_pointing_to_missing_field_nested(self):
2901 class Model(models.Model):
2902 class Meta:
2903 constraints = [
2904 models.UniqueConstraint(Abs(Round("missing_field")), name="name"),
2905 ]
2906
2907 self.assertEqual(
2908 Model.check(databases=self.databases),
2909 [
2910 Error(
2911 "'constraints' refers to the nonexistent field 'missing_field'.",
2912 obj=Model,
2913 id="models.E012",
2914 ),
2915 ],
2916 )
2917
2918 @skipUnlessDBFeature("supports_expression_indexes")
2919 def test_func_unique_constraint_pointing_to_m2m_field(self):
2920 class Model(models.Model):
2921 m2m = models.ManyToManyField("self")
2922
2923 class Meta:
2924 constraints = [models.UniqueConstraint(Lower("m2m"), name="name")]
2925
2926 self.assertEqual(
2927 Model.check(databases=self.databases),
2928 [
2929 Error(
2930 "'constraints' refers to a ManyToManyField 'm2m', but "
2931 "ManyToManyFields are not permitted in 'constraints'.",
2932 obj=Model,
2933 id="models.E013",
2934 ),
2935 ],
2936 )
2937
2938 @skipUnlessDBFeature("supports_expression_indexes")
2939 def test_func_unique_constraint_pointing_to_non_local_field(self):
2940 class Foo(models.Model):
2941 field1 = models.CharField(max_length=15)
2942
2943 class Bar(Foo):
2944 class Meta:
2945 constraints = [models.UniqueConstraint(Lower("field1"), name="name")]
2946
2947 self.assertEqual(
2948 Bar.check(databases=self.databases),
2949 [
2950 Error(
2951 "'constraints' refers to field 'field1' which is not local to "
2952 "model 'Bar'.",
2953 hint="This issue may be caused by multi-table inheritance.",
2954 obj=Bar,
2955 id="models.E016",
2956 ),
2957 ],
2958 )
2959
2960 @skipUnlessDBFeature("supports_expression_indexes")
2961 def test_func_unique_constraint_pointing_to_fk(self):
2962 class Foo(models.Model):
2963 id = models.CharField(primary_key=True, max_length=255)
2964
2965 class Bar(models.Model):
2966 foo_1 = models.ForeignKey(Foo, models.CASCADE, related_name="bar_1")
2967 foo_2 = models.ForeignKey(Foo, models.CASCADE, related_name="bar_2")
2968
2969 class Meta:
2970 constraints = [
2971 models.UniqueConstraint(
2972 Lower("foo_1_id"),
2973 Lower("foo_2"),
2974 name="name",
2975 ),
2976 ]
2977
2978 self.assertEqual(Bar.check(databases=self.databases), [])
2979
2980 @skipUnlessDBFeature("supports_expression_indexes")
2981 def test_func_unique_constraint_pointing_composite_primary_key(self):
2982 class Model(models.Model):
2983 pk = models.CompositePrimaryKey("version", "name")
2984 version = models.IntegerField()
2985 name = models.CharField(max_length=20)
2986
2987 class Meta:
2988 constraints = [models.UniqueConstraint(Abs("pk"), name="name")]
2989
2990 self.assertEqual(
2991 Model.check(databases=self.databases),
2992 [
2993 Error(
2994 "'constraints' refers to a CompositePrimaryKey 'pk', but "
2995 "CompositePrimaryKeys are not permitted in 'constraints'.",
2996 obj=Model,
2997 id="models.E048",
2998 ),
2999 ],
3000 )