test_models.py 98 KB

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