tests.py 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531
  1. import datetime
  2. import pickle
  3. from io import StringIO
  4. from operator import attrgetter
  5. from unittest.mock import Mock
  6. from django.contrib.auth.models import User
  7. from django.contrib.contenttypes.models import ContentType
  8. from django.core import management
  9. from django.db import DEFAULT_DB_ALIAS, router, transaction
  10. from django.db.models import signals
  11. from django.db.utils import ConnectionRouter
  12. from django.test import SimpleTestCase, TestCase, override_settings
  13. from .models import Book, Person, Pet, Review, UserProfile
  14. from .routers import AuthRouter, TestRouter, WriteRouter
  15. class QueryTestCase(TestCase):
  16. databases = {"default", "other"}
  17. def test_db_selection(self):
  18. "Querysets will use the default database by default"
  19. self.assertEqual(Book.objects.db, DEFAULT_DB_ALIAS)
  20. self.assertEqual(Book.objects.all().db, DEFAULT_DB_ALIAS)
  21. self.assertEqual(Book.objects.using("other").db, "other")
  22. self.assertEqual(Book.objects.db_manager("other").db, "other")
  23. self.assertEqual(Book.objects.db_manager("other").all().db, "other")
  24. def test_default_creation(self):
  25. "Objects created on the default database don't leak onto other databases"
  26. # Create a book on the default database using create()
  27. Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
  28. # Create a book on the default database using a save
  29. dive = Book()
  30. dive.title = "Dive into Python"
  31. dive.published = datetime.date(2009, 5, 4)
  32. dive.save()
  33. # Book exists on the default database, but not on other database
  34. try:
  35. Book.objects.get(title="Pro Django")
  36. Book.objects.using("default").get(title="Pro Django")
  37. except Book.DoesNotExist:
  38. self.fail('"Pro Django" should exist on default database')
  39. with self.assertRaises(Book.DoesNotExist):
  40. Book.objects.using("other").get(title="Pro Django")
  41. try:
  42. Book.objects.get(title="Dive into Python")
  43. Book.objects.using("default").get(title="Dive into Python")
  44. except Book.DoesNotExist:
  45. self.fail('"Dive into Python" should exist on default database')
  46. with self.assertRaises(Book.DoesNotExist):
  47. Book.objects.using("other").get(title="Dive into Python")
  48. def test_other_creation(self):
  49. "Objects created on another database don't leak onto the default database"
  50. # Create a book on the second database
  51. Book.objects.using("other").create(
  52. title="Pro Django", published=datetime.date(2008, 12, 16)
  53. )
  54. # Create a book on the default database using a save
  55. dive = Book()
  56. dive.title = "Dive into Python"
  57. dive.published = datetime.date(2009, 5, 4)
  58. dive.save(using="other")
  59. # Book exists on the default database, but not on other database
  60. try:
  61. Book.objects.using("other").get(title="Pro Django")
  62. except Book.DoesNotExist:
  63. self.fail('"Pro Django" should exist on other database')
  64. with self.assertRaises(Book.DoesNotExist):
  65. Book.objects.get(title="Pro Django")
  66. with self.assertRaises(Book.DoesNotExist):
  67. Book.objects.using("default").get(title="Pro Django")
  68. try:
  69. Book.objects.using("other").get(title="Dive into Python")
  70. except Book.DoesNotExist:
  71. self.fail('"Dive into Python" should exist on other database')
  72. with self.assertRaises(Book.DoesNotExist):
  73. Book.objects.get(title="Dive into Python")
  74. with self.assertRaises(Book.DoesNotExist):
  75. Book.objects.using("default").get(title="Dive into Python")
  76. def test_refresh(self):
  77. dive = Book(title="Dive into Python", published=datetime.date(2009, 5, 4))
  78. dive.save(using="other")
  79. dive2 = Book.objects.using("other").get()
  80. dive2.title = "Dive into Python (on default)"
  81. dive2.save(using="default")
  82. dive.refresh_from_db()
  83. self.assertEqual(dive.title, "Dive into Python")
  84. dive.refresh_from_db(using="default")
  85. self.assertEqual(dive.title, "Dive into Python (on default)")
  86. self.assertEqual(dive._state.db, "default")
  87. def test_refresh_router_instance_hint(self):
  88. router = Mock()
  89. router.db_for_read.return_value = None
  90. book = Book.objects.create(
  91. title="Dive Into Python", published=datetime.date(1957, 10, 12)
  92. )
  93. with self.settings(DATABASE_ROUTERS=[router]):
  94. book.refresh_from_db()
  95. router.db_for_read.assert_called_once_with(Book, instance=book)
  96. def test_basic_queries(self):
  97. "Queries are constrained to a single database"
  98. dive = Book.objects.using("other").create(
  99. title="Dive into Python", published=datetime.date(2009, 5, 4)
  100. )
  101. dive = Book.objects.using("other").get(published=datetime.date(2009, 5, 4))
  102. self.assertEqual(dive.title, "Dive into Python")
  103. with self.assertRaises(Book.DoesNotExist):
  104. Book.objects.using("default").get(published=datetime.date(2009, 5, 4))
  105. dive = Book.objects.using("other").get(title__icontains="dive")
  106. self.assertEqual(dive.title, "Dive into Python")
  107. with self.assertRaises(Book.DoesNotExist):
  108. Book.objects.using("default").get(title__icontains="dive")
  109. dive = Book.objects.using("other").get(title__iexact="dive INTO python")
  110. self.assertEqual(dive.title, "Dive into Python")
  111. with self.assertRaises(Book.DoesNotExist):
  112. Book.objects.using("default").get(title__iexact="dive INTO python")
  113. dive = Book.objects.using("other").get(published__year=2009)
  114. self.assertEqual(dive.title, "Dive into Python")
  115. self.assertEqual(dive.published, datetime.date(2009, 5, 4))
  116. with self.assertRaises(Book.DoesNotExist):
  117. Book.objects.using("default").get(published__year=2009)
  118. years = Book.objects.using("other").dates("published", "year")
  119. self.assertEqual([o.year for o in years], [2009])
  120. years = Book.objects.using("default").dates("published", "year")
  121. self.assertEqual([o.year for o in years], [])
  122. months = Book.objects.using("other").dates("published", "month")
  123. self.assertEqual([o.month for o in months], [5])
  124. months = Book.objects.using("default").dates("published", "month")
  125. self.assertEqual([o.month for o in months], [])
  126. def test_m2m_separation(self):
  127. "M2M fields are constrained to a single database"
  128. # Create a book and author on the default database
  129. pro = Book.objects.create(
  130. title="Pro Django", published=datetime.date(2008, 12, 16)
  131. )
  132. marty = Person.objects.create(name="Marty Alchin")
  133. # Create a book and author on the other database
  134. dive = Book.objects.using("other").create(
  135. title="Dive into Python", published=datetime.date(2009, 5, 4)
  136. )
  137. mark = Person.objects.using("other").create(name="Mark Pilgrim")
  138. # Save the author relations
  139. pro.authors.set([marty])
  140. dive.authors.set([mark])
  141. # Inspect the m2m tables directly.
  142. # There should be 1 entry in each database
  143. self.assertEqual(Book.authors.through.objects.using("default").count(), 1)
  144. self.assertEqual(Book.authors.through.objects.using("other").count(), 1)
  145. # Queries work across m2m joins
  146. self.assertEqual(
  147. list(
  148. Book.objects.using("default")
  149. .filter(authors__name="Marty Alchin")
  150. .values_list("title", flat=True)
  151. ),
  152. ["Pro Django"],
  153. )
  154. self.assertEqual(
  155. list(
  156. Book.objects.using("other")
  157. .filter(authors__name="Marty Alchin")
  158. .values_list("title", flat=True)
  159. ),
  160. [],
  161. )
  162. self.assertEqual(
  163. list(
  164. Book.objects.using("default")
  165. .filter(authors__name="Mark Pilgrim")
  166. .values_list("title", flat=True)
  167. ),
  168. [],
  169. )
  170. self.assertEqual(
  171. list(
  172. Book.objects.using("other")
  173. .filter(authors__name="Mark Pilgrim")
  174. .values_list("title", flat=True)
  175. ),
  176. ["Dive into Python"],
  177. )
  178. # Reget the objects to clear caches
  179. dive = Book.objects.using("other").get(title="Dive into Python")
  180. mark = Person.objects.using("other").get(name="Mark Pilgrim")
  181. # Retrieve related object by descriptor. Related objects should be
  182. # database-bound.
  183. self.assertEqual(
  184. list(dive.authors.values_list("name", flat=True)), ["Mark Pilgrim"]
  185. )
  186. self.assertEqual(
  187. list(mark.book_set.values_list("title", flat=True)),
  188. ["Dive into Python"],
  189. )
  190. def test_m2m_forward_operations(self):
  191. "M2M forward manipulations are all constrained to a single DB"
  192. # Create a book and author on the other database
  193. dive = Book.objects.using("other").create(
  194. title="Dive into Python", published=datetime.date(2009, 5, 4)
  195. )
  196. mark = Person.objects.using("other").create(name="Mark Pilgrim")
  197. # Save the author relations
  198. dive.authors.set([mark])
  199. # Add a second author
  200. john = Person.objects.using("other").create(name="John Smith")
  201. self.assertEqual(
  202. list(
  203. Book.objects.using("other")
  204. .filter(authors__name="John Smith")
  205. .values_list("title", flat=True)
  206. ),
  207. [],
  208. )
  209. dive.authors.add(john)
  210. self.assertEqual(
  211. list(
  212. Book.objects.using("other")
  213. .filter(authors__name="Mark Pilgrim")
  214. .values_list("title", flat=True)
  215. ),
  216. ["Dive into Python"],
  217. )
  218. self.assertEqual(
  219. list(
  220. Book.objects.using("other")
  221. .filter(authors__name="John Smith")
  222. .values_list("title", flat=True)
  223. ),
  224. ["Dive into Python"],
  225. )
  226. # Remove the second author
  227. dive.authors.remove(john)
  228. self.assertEqual(
  229. list(
  230. Book.objects.using("other")
  231. .filter(authors__name="Mark Pilgrim")
  232. .values_list("title", flat=True)
  233. ),
  234. ["Dive into Python"],
  235. )
  236. self.assertEqual(
  237. list(
  238. Book.objects.using("other")
  239. .filter(authors__name="John Smith")
  240. .values_list("title", flat=True)
  241. ),
  242. [],
  243. )
  244. # Clear all authors
  245. dive.authors.clear()
  246. self.assertEqual(
  247. list(
  248. Book.objects.using("other")
  249. .filter(authors__name="Mark Pilgrim")
  250. .values_list("title", flat=True)
  251. ),
  252. [],
  253. )
  254. self.assertEqual(
  255. list(
  256. Book.objects.using("other")
  257. .filter(authors__name="John Smith")
  258. .values_list("title", flat=True)
  259. ),
  260. [],
  261. )
  262. # Create an author through the m2m interface
  263. dive.authors.create(name="Jane Brown")
  264. self.assertEqual(
  265. list(
  266. Book.objects.using("other")
  267. .filter(authors__name="Mark Pilgrim")
  268. .values_list("title", flat=True)
  269. ),
  270. [],
  271. )
  272. self.assertEqual(
  273. list(
  274. Book.objects.using("other")
  275. .filter(authors__name="Jane Brown")
  276. .values_list("title", flat=True)
  277. ),
  278. ["Dive into Python"],
  279. )
  280. def test_m2m_reverse_operations(self):
  281. "M2M reverse manipulations are all constrained to a single DB"
  282. # Create a book and author on the other database
  283. dive = Book.objects.using("other").create(
  284. title="Dive into Python", published=datetime.date(2009, 5, 4)
  285. )
  286. mark = Person.objects.using("other").create(name="Mark Pilgrim")
  287. # Save the author relations
  288. dive.authors.set([mark])
  289. # Create a second book on the other database
  290. grease = Book.objects.using("other").create(
  291. title="Greasemonkey Hacks", published=datetime.date(2005, 11, 1)
  292. )
  293. # Add a books to the m2m
  294. mark.book_set.add(grease)
  295. self.assertEqual(
  296. list(
  297. Person.objects.using("other")
  298. .filter(book__title="Dive into Python")
  299. .values_list("name", flat=True)
  300. ),
  301. ["Mark Pilgrim"],
  302. )
  303. self.assertEqual(
  304. list(
  305. Person.objects.using("other")
  306. .filter(book__title="Greasemonkey Hacks")
  307. .values_list("name", flat=True)
  308. ),
  309. ["Mark Pilgrim"],
  310. )
  311. # Remove a book from the m2m
  312. mark.book_set.remove(grease)
  313. self.assertEqual(
  314. list(
  315. Person.objects.using("other")
  316. .filter(book__title="Dive into Python")
  317. .values_list("name", flat=True)
  318. ),
  319. ["Mark Pilgrim"],
  320. )
  321. self.assertEqual(
  322. list(
  323. Person.objects.using("other")
  324. .filter(book__title="Greasemonkey Hacks")
  325. .values_list("name", flat=True)
  326. ),
  327. [],
  328. )
  329. # Clear the books associated with mark
  330. mark.book_set.clear()
  331. self.assertEqual(
  332. list(
  333. Person.objects.using("other")
  334. .filter(book__title="Dive into Python")
  335. .values_list("name", flat=True)
  336. ),
  337. [],
  338. )
  339. self.assertEqual(
  340. list(
  341. Person.objects.using("other")
  342. .filter(book__title="Greasemonkey Hacks")
  343. .values_list("name", flat=True)
  344. ),
  345. [],
  346. )
  347. # Create a book through the m2m interface
  348. mark.book_set.create(
  349. title="Dive into HTML5", published=datetime.date(2020, 1, 1)
  350. )
  351. self.assertEqual(
  352. list(
  353. Person.objects.using("other")
  354. .filter(book__title="Dive into Python")
  355. .values_list("name", flat=True)
  356. ),
  357. [],
  358. )
  359. self.assertEqual(
  360. list(
  361. Person.objects.using("other")
  362. .filter(book__title="Dive into HTML5")
  363. .values_list("name", flat=True)
  364. ),
  365. ["Mark Pilgrim"],
  366. )
  367. def test_m2m_cross_database_protection(self):
  368. "Operations that involve sharing M2M objects across databases raise an error"
  369. # Create a book and author on the default database
  370. pro = Book.objects.create(
  371. title="Pro Django", published=datetime.date(2008, 12, 16)
  372. )
  373. marty = Person.objects.create(name="Marty Alchin")
  374. # Create a book and author on the other database
  375. dive = Book.objects.using("other").create(
  376. title="Dive into Python", published=datetime.date(2009, 5, 4)
  377. )
  378. mark = Person.objects.using("other").create(name="Mark Pilgrim")
  379. # Set a foreign key set with an object from a different database
  380. msg = (
  381. 'Cannot assign "<Person: Marty Alchin>": the current database '
  382. "router prevents this relation."
  383. )
  384. with self.assertRaisesMessage(ValueError, msg):
  385. with transaction.atomic(using="default"):
  386. marty.edited.set([pro, dive])
  387. # Add to an m2m with an object from a different database
  388. msg = (
  389. 'Cannot add "<Book: Dive into Python>": instance is on '
  390. 'database "default", value is on database "other"'
  391. )
  392. with self.assertRaisesMessage(ValueError, msg):
  393. with transaction.atomic(using="default"):
  394. marty.book_set.add(dive)
  395. # Set a m2m with an object from a different database
  396. with self.assertRaisesMessage(ValueError, msg):
  397. with transaction.atomic(using="default"):
  398. marty.book_set.set([pro, dive])
  399. # Add to a reverse m2m with an object from a different database
  400. msg = (
  401. 'Cannot add "<Person: Marty Alchin>": instance is on '
  402. 'database "other", value is on database "default"'
  403. )
  404. with self.assertRaisesMessage(ValueError, msg):
  405. with transaction.atomic(using="other"):
  406. dive.authors.add(marty)
  407. # Set a reverse m2m with an object from a different database
  408. with self.assertRaisesMessage(ValueError, msg):
  409. with transaction.atomic(using="other"):
  410. dive.authors.set([mark, marty])
  411. def test_m2m_deletion(self):
  412. "Cascaded deletions of m2m relations issue queries on the right database"
  413. # Create a book and author on the other database
  414. dive = Book.objects.using("other").create(
  415. title="Dive into Python", published=datetime.date(2009, 5, 4)
  416. )
  417. mark = Person.objects.using("other").create(name="Mark Pilgrim")
  418. dive.authors.set([mark])
  419. # Check the initial state
  420. self.assertEqual(Person.objects.using("default").count(), 0)
  421. self.assertEqual(Book.objects.using("default").count(), 0)
  422. self.assertEqual(Book.authors.through.objects.using("default").count(), 0)
  423. self.assertEqual(Person.objects.using("other").count(), 1)
  424. self.assertEqual(Book.objects.using("other").count(), 1)
  425. self.assertEqual(Book.authors.through.objects.using("other").count(), 1)
  426. # Delete the object on the other database
  427. dive.delete(using="other")
  428. self.assertEqual(Person.objects.using("default").count(), 0)
  429. self.assertEqual(Book.objects.using("default").count(), 0)
  430. self.assertEqual(Book.authors.through.objects.using("default").count(), 0)
  431. # The person still exists ...
  432. self.assertEqual(Person.objects.using("other").count(), 1)
  433. # ... but the book has been deleted
  434. self.assertEqual(Book.objects.using("other").count(), 0)
  435. # ... and the relationship object has also been deleted.
  436. self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
  437. # Now try deletion in the reverse direction. Set up the relation again
  438. dive = Book.objects.using("other").create(
  439. title="Dive into Python", published=datetime.date(2009, 5, 4)
  440. )
  441. dive.authors.set([mark])
  442. # Check the initial state
  443. self.assertEqual(Person.objects.using("default").count(), 0)
  444. self.assertEqual(Book.objects.using("default").count(), 0)
  445. self.assertEqual(Book.authors.through.objects.using("default").count(), 0)
  446. self.assertEqual(Person.objects.using("other").count(), 1)
  447. self.assertEqual(Book.objects.using("other").count(), 1)
  448. self.assertEqual(Book.authors.through.objects.using("other").count(), 1)
  449. # Delete the object on the other database
  450. mark.delete(using="other")
  451. self.assertEqual(Person.objects.using("default").count(), 0)
  452. self.assertEqual(Book.objects.using("default").count(), 0)
  453. self.assertEqual(Book.authors.through.objects.using("default").count(), 0)
  454. # The person has been deleted ...
  455. self.assertEqual(Person.objects.using("other").count(), 0)
  456. # ... but the book still exists
  457. self.assertEqual(Book.objects.using("other").count(), 1)
  458. # ... and the relationship object has been deleted.
  459. self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
  460. def test_foreign_key_separation(self):
  461. "FK fields are constrained to a single database"
  462. # Create a book and author on the default database
  463. pro = Book.objects.create(
  464. title="Pro Django", published=datetime.date(2008, 12, 16)
  465. )
  466. george = Person.objects.create(name="George Vilches")
  467. # Create a book and author on the other database
  468. dive = Book.objects.using("other").create(
  469. title="Dive into Python", published=datetime.date(2009, 5, 4)
  470. )
  471. chris = Person.objects.using("other").create(name="Chris Mills")
  472. # Save the author's favorite books
  473. pro.editor = george
  474. pro.save()
  475. dive.editor = chris
  476. dive.save()
  477. pro = Book.objects.using("default").get(title="Pro Django")
  478. self.assertEqual(pro.editor.name, "George Vilches")
  479. dive = Book.objects.using("other").get(title="Dive into Python")
  480. self.assertEqual(dive.editor.name, "Chris Mills")
  481. # Queries work across foreign key joins
  482. self.assertEqual(
  483. list(
  484. Person.objects.using("default")
  485. .filter(edited__title="Pro Django")
  486. .values_list("name", flat=True)
  487. ),
  488. ["George Vilches"],
  489. )
  490. self.assertEqual(
  491. list(
  492. Person.objects.using("other")
  493. .filter(edited__title="Pro Django")
  494. .values_list("name", flat=True)
  495. ),
  496. [],
  497. )
  498. self.assertEqual(
  499. list(
  500. Person.objects.using("default")
  501. .filter(edited__title="Dive into Python")
  502. .values_list("name", flat=True)
  503. ),
  504. [],
  505. )
  506. self.assertEqual(
  507. list(
  508. Person.objects.using("other")
  509. .filter(edited__title="Dive into Python")
  510. .values_list("name", flat=True)
  511. ),
  512. ["Chris Mills"],
  513. )
  514. # Reget the objects to clear caches
  515. chris = Person.objects.using("other").get(name="Chris Mills")
  516. dive = Book.objects.using("other").get(title="Dive into Python")
  517. # Retrieve related object by descriptor. Related objects should be
  518. # database-bound.
  519. self.assertEqual(
  520. list(chris.edited.values_list("title", flat=True)), ["Dive into Python"]
  521. )
  522. def test_foreign_key_reverse_operations(self):
  523. "FK reverse manipulations are all constrained to a single DB"
  524. dive = Book.objects.using("other").create(
  525. title="Dive into Python", published=datetime.date(2009, 5, 4)
  526. )
  527. chris = Person.objects.using("other").create(name="Chris Mills")
  528. # Save the author relations
  529. dive.editor = chris
  530. dive.save()
  531. # Add a second book edited by chris
  532. html5 = Book.objects.using("other").create(
  533. title="Dive into HTML5", published=datetime.date(2010, 3, 15)
  534. )
  535. self.assertEqual(
  536. list(
  537. Person.objects.using("other")
  538. .filter(edited__title="Dive into HTML5")
  539. .values_list("name", flat=True)
  540. ),
  541. [],
  542. )
  543. chris.edited.add(html5)
  544. self.assertEqual(
  545. list(
  546. Person.objects.using("other")
  547. .filter(edited__title="Dive into HTML5")
  548. .values_list("name", flat=True)
  549. ),
  550. ["Chris Mills"],
  551. )
  552. self.assertEqual(
  553. list(
  554. Person.objects.using("other")
  555. .filter(edited__title="Dive into Python")
  556. .values_list("name", flat=True)
  557. ),
  558. ["Chris Mills"],
  559. )
  560. # Remove the second editor
  561. chris.edited.remove(html5)
  562. self.assertEqual(
  563. list(
  564. Person.objects.using("other")
  565. .filter(edited__title="Dive into HTML5")
  566. .values_list("name", flat=True)
  567. ),
  568. [],
  569. )
  570. self.assertEqual(
  571. list(
  572. Person.objects.using("other")
  573. .filter(edited__title="Dive into Python")
  574. .values_list("name", flat=True)
  575. ),
  576. ["Chris Mills"],
  577. )
  578. # Clear all edited books
  579. chris.edited.clear()
  580. self.assertEqual(
  581. list(
  582. Person.objects.using("other")
  583. .filter(edited__title="Dive into HTML5")
  584. .values_list("name", flat=True)
  585. ),
  586. [],
  587. )
  588. self.assertEqual(
  589. list(
  590. Person.objects.using("other")
  591. .filter(edited__title="Dive into Python")
  592. .values_list("name", flat=True)
  593. ),
  594. [],
  595. )
  596. # Create an author through the m2m interface
  597. chris.edited.create(
  598. title="Dive into Water", published=datetime.date(2010, 3, 15)
  599. )
  600. self.assertEqual(
  601. list(
  602. Person.objects.using("other")
  603. .filter(edited__title="Dive into HTML5")
  604. .values_list("name", flat=True)
  605. ),
  606. [],
  607. )
  608. self.assertEqual(
  609. list(
  610. Person.objects.using("other")
  611. .filter(edited__title="Dive into Water")
  612. .values_list("name", flat=True)
  613. ),
  614. ["Chris Mills"],
  615. )
  616. self.assertEqual(
  617. list(
  618. Person.objects.using("other")
  619. .filter(edited__title="Dive into Python")
  620. .values_list("name", flat=True)
  621. ),
  622. [],
  623. )
  624. def test_foreign_key_cross_database_protection(self):
  625. "Operations that involve sharing FK objects across databases raise an error"
  626. # Create a book and author on the default database
  627. pro = Book.objects.create(
  628. title="Pro Django", published=datetime.date(2008, 12, 16)
  629. )
  630. marty = Person.objects.create(name="Marty Alchin")
  631. # Create a book and author on the other database
  632. dive = Book.objects.using("other").create(
  633. title="Dive into Python", published=datetime.date(2009, 5, 4)
  634. )
  635. # Set a foreign key with an object from a different database
  636. msg = (
  637. 'Cannot assign "<Person: Marty Alchin>": the current database '
  638. "router prevents this relation."
  639. )
  640. with self.assertRaisesMessage(ValueError, msg):
  641. dive.editor = marty
  642. # Set a foreign key set with an object from a different database
  643. with self.assertRaisesMessage(ValueError, msg):
  644. with transaction.atomic(using="default"):
  645. marty.edited.set([pro, dive])
  646. # Add to a foreign key set with an object from a different database
  647. with self.assertRaisesMessage(ValueError, msg):
  648. with transaction.atomic(using="default"):
  649. marty.edited.add(dive)
  650. def test_foreign_key_deletion(self):
  651. """
  652. Cascaded deletions of Foreign Key relations issue queries on the right
  653. database.
  654. """
  655. mark = Person.objects.using("other").create(name="Mark Pilgrim")
  656. Pet.objects.using("other").create(name="Fido", owner=mark)
  657. # Check the initial state
  658. self.assertEqual(Person.objects.using("default").count(), 0)
  659. self.assertEqual(Pet.objects.using("default").count(), 0)
  660. self.assertEqual(Person.objects.using("other").count(), 1)
  661. self.assertEqual(Pet.objects.using("other").count(), 1)
  662. # Delete the person object, which will cascade onto the pet
  663. mark.delete(using="other")
  664. self.assertEqual(Person.objects.using("default").count(), 0)
  665. self.assertEqual(Pet.objects.using("default").count(), 0)
  666. # Both the pet and the person have been deleted from the right database
  667. self.assertEqual(Person.objects.using("other").count(), 0)
  668. self.assertEqual(Pet.objects.using("other").count(), 0)
  669. def test_foreign_key_validation(self):
  670. "ForeignKey.validate() uses the correct database"
  671. mickey = Person.objects.using("other").create(name="Mickey")
  672. pluto = Pet.objects.using("other").create(name="Pluto", owner=mickey)
  673. self.assertIsNone(pluto.full_clean())
  674. # Any router that accesses `model` in db_for_read() works here.
  675. @override_settings(DATABASE_ROUTERS=[AuthRouter()])
  676. def test_foreign_key_validation_with_router(self):
  677. """
  678. ForeignKey.validate() passes `model` to db_for_read() even if
  679. model_instance=None.
  680. """
  681. mickey = Person.objects.create(name="Mickey")
  682. owner_field = Pet._meta.get_field("owner")
  683. self.assertEqual(owner_field.clean(mickey.pk, None), mickey.pk)
  684. def test_o2o_separation(self):
  685. "OneToOne fields are constrained to a single database"
  686. # Create a user and profile on the default database
  687. alice = User.objects.db_manager("default").create_user(
  688. "alice", "alice@example.com"
  689. )
  690. alice_profile = UserProfile.objects.using("default").create(
  691. user=alice, flavor="chocolate"
  692. )
  693. # Create a user and profile on the other database
  694. bob = User.objects.db_manager("other").create_user("bob", "bob@example.com")
  695. bob_profile = UserProfile.objects.using("other").create(
  696. user=bob, flavor="crunchy frog"
  697. )
  698. # Retrieve related objects; queries should be database constrained
  699. alice = User.objects.using("default").get(username="alice")
  700. self.assertEqual(alice.userprofile.flavor, "chocolate")
  701. bob = User.objects.using("other").get(username="bob")
  702. self.assertEqual(bob.userprofile.flavor, "crunchy frog")
  703. # Queries work across joins
  704. self.assertEqual(
  705. list(
  706. User.objects.using("default")
  707. .filter(userprofile__flavor="chocolate")
  708. .values_list("username", flat=True)
  709. ),
  710. ["alice"],
  711. )
  712. self.assertEqual(
  713. list(
  714. User.objects.using("other")
  715. .filter(userprofile__flavor="chocolate")
  716. .values_list("username", flat=True)
  717. ),
  718. [],
  719. )
  720. self.assertEqual(
  721. list(
  722. User.objects.using("default")
  723. .filter(userprofile__flavor="crunchy frog")
  724. .values_list("username", flat=True)
  725. ),
  726. [],
  727. )
  728. self.assertEqual(
  729. list(
  730. User.objects.using("other")
  731. .filter(userprofile__flavor="crunchy frog")
  732. .values_list("username", flat=True)
  733. ),
  734. ["bob"],
  735. )
  736. # Reget the objects to clear caches
  737. alice_profile = UserProfile.objects.using("default").get(flavor="chocolate")
  738. bob_profile = UserProfile.objects.using("other").get(flavor="crunchy frog")
  739. # Retrieve related object by descriptor. Related objects should be
  740. # database-bound.
  741. self.assertEqual(alice_profile.user.username, "alice")
  742. self.assertEqual(bob_profile.user.username, "bob")
  743. def test_o2o_cross_database_protection(self):
  744. "Operations that involve sharing FK objects across databases raise an error"
  745. # Create a user and profile on the default database
  746. alice = User.objects.db_manager("default").create_user(
  747. "alice", "alice@example.com"
  748. )
  749. # Create a user and profile on the other database
  750. bob = User.objects.db_manager("other").create_user("bob", "bob@example.com")
  751. # Set a one-to-one relation with an object from a different database
  752. alice_profile = UserProfile.objects.using("default").create(
  753. user=alice, flavor="chocolate"
  754. )
  755. msg = (
  756. 'Cannot assign "%r": the current database router prevents this '
  757. "relation." % alice_profile
  758. )
  759. with self.assertRaisesMessage(ValueError, msg):
  760. bob.userprofile = alice_profile
  761. # BUT! if you assign a FK object when the base object hasn't
  762. # been saved yet, you implicitly assign the database for the
  763. # base object.
  764. bob_profile = UserProfile.objects.using("other").create(
  765. user=bob, flavor="crunchy frog"
  766. )
  767. new_bob_profile = UserProfile(flavor="spring surprise")
  768. # assigning a profile requires an explicit pk as the object isn't saved
  769. charlie = User(pk=51, username="charlie", email="charlie@example.com")
  770. charlie.set_unusable_password()
  771. # initially, no db assigned
  772. self.assertIsNone(new_bob_profile._state.db)
  773. self.assertIsNone(charlie._state.db)
  774. # old object comes from 'other', so the new object is set to use 'other'...
  775. new_bob_profile.user = bob
  776. charlie.userprofile = bob_profile
  777. self.assertEqual(new_bob_profile._state.db, "other")
  778. self.assertEqual(charlie._state.db, "other")
  779. # ... but it isn't saved yet
  780. self.assertEqual(
  781. list(User.objects.using("other").values_list("username", flat=True)),
  782. ["bob"],
  783. )
  784. self.assertEqual(
  785. list(UserProfile.objects.using("other").values_list("flavor", flat=True)),
  786. ["crunchy frog"],
  787. )
  788. # When saved (no using required), new objects goes to 'other'
  789. charlie.save()
  790. bob_profile.save()
  791. new_bob_profile.save()
  792. self.assertEqual(
  793. list(User.objects.using("default").values_list("username", flat=True)),
  794. ["alice"],
  795. )
  796. self.assertEqual(
  797. list(User.objects.using("other").values_list("username", flat=True)),
  798. ["bob", "charlie"],
  799. )
  800. self.assertEqual(
  801. list(UserProfile.objects.using("default").values_list("flavor", flat=True)),
  802. ["chocolate"],
  803. )
  804. self.assertEqual(
  805. list(UserProfile.objects.using("other").values_list("flavor", flat=True)),
  806. ["crunchy frog", "spring surprise"],
  807. )
  808. # This also works if you assign the O2O relation in the constructor
  809. denise = User.objects.db_manager("other").create_user(
  810. "denise", "denise@example.com"
  811. )
  812. denise_profile = UserProfile(flavor="tofu", user=denise)
  813. self.assertEqual(denise_profile._state.db, "other")
  814. # ... but it isn't saved yet
  815. self.assertEqual(
  816. list(UserProfile.objects.using("default").values_list("flavor", flat=True)),
  817. ["chocolate"],
  818. )
  819. self.assertEqual(
  820. list(UserProfile.objects.using("other").values_list("flavor", flat=True)),
  821. ["crunchy frog", "spring surprise"],
  822. )
  823. # When saved, the new profile goes to 'other'
  824. denise_profile.save()
  825. self.assertEqual(
  826. list(UserProfile.objects.using("default").values_list("flavor", flat=True)),
  827. ["chocolate"],
  828. )
  829. self.assertEqual(
  830. list(UserProfile.objects.using("other").values_list("flavor", flat=True)),
  831. ["crunchy frog", "spring surprise", "tofu"],
  832. )
  833. def test_generic_key_separation(self):
  834. "Generic fields are constrained to a single database"
  835. # Create a book and author on the default database
  836. pro = Book.objects.create(
  837. title="Pro Django", published=datetime.date(2008, 12, 16)
  838. )
  839. review1 = Review.objects.create(source="Python Monthly", content_object=pro)
  840. # Create a book and author on the other database
  841. dive = Book.objects.using("other").create(
  842. title="Dive into Python", published=datetime.date(2009, 5, 4)
  843. )
  844. review2 = Review.objects.using("other").create(
  845. source="Python Weekly", content_object=dive
  846. )
  847. review1 = Review.objects.using("default").get(source="Python Monthly")
  848. self.assertEqual(review1.content_object.title, "Pro Django")
  849. review2 = Review.objects.using("other").get(source="Python Weekly")
  850. self.assertEqual(review2.content_object.title, "Dive into Python")
  851. # Reget the objects to clear caches
  852. dive = Book.objects.using("other").get(title="Dive into Python")
  853. # Retrieve related object by descriptor. Related objects should be
  854. # database-bound.
  855. self.assertEqual(
  856. list(dive.reviews.values_list("source", flat=True)), ["Python Weekly"]
  857. )
  858. def test_generic_key_reverse_operations(self):
  859. "Generic reverse manipulations are all constrained to a single DB"
  860. dive = Book.objects.using("other").create(
  861. title="Dive into Python", published=datetime.date(2009, 5, 4)
  862. )
  863. temp = Book.objects.using("other").create(
  864. title="Temp", published=datetime.date(2009, 5, 4)
  865. )
  866. review1 = Review.objects.using("other").create(
  867. source="Python Weekly", content_object=dive
  868. )
  869. review2 = Review.objects.using("other").create(
  870. source="Python Monthly", content_object=temp
  871. )
  872. self.assertEqual(
  873. list(
  874. Review.objects.using("default")
  875. .filter(object_id=dive.pk)
  876. .values_list("source", flat=True)
  877. ),
  878. [],
  879. )
  880. self.assertEqual(
  881. list(
  882. Review.objects.using("other")
  883. .filter(object_id=dive.pk)
  884. .values_list("source", flat=True)
  885. ),
  886. ["Python Weekly"],
  887. )
  888. # Add a second review
  889. dive.reviews.add(review2)
  890. self.assertEqual(
  891. list(
  892. Review.objects.using("default")
  893. .filter(object_id=dive.pk)
  894. .values_list("source", flat=True)
  895. ),
  896. [],
  897. )
  898. self.assertEqual(
  899. list(
  900. Review.objects.using("other")
  901. .filter(object_id=dive.pk)
  902. .values_list("source", flat=True)
  903. ),
  904. ["Python Monthly", "Python Weekly"],
  905. )
  906. # Remove the second author
  907. dive.reviews.remove(review1)
  908. self.assertEqual(
  909. list(
  910. Review.objects.using("default")
  911. .filter(object_id=dive.pk)
  912. .values_list("source", flat=True)
  913. ),
  914. [],
  915. )
  916. self.assertEqual(
  917. list(
  918. Review.objects.using("other")
  919. .filter(object_id=dive.pk)
  920. .values_list("source", flat=True)
  921. ),
  922. ["Python Monthly"],
  923. )
  924. # Clear all reviews
  925. dive.reviews.clear()
  926. self.assertEqual(
  927. list(
  928. Review.objects.using("default")
  929. .filter(object_id=dive.pk)
  930. .values_list("source", flat=True)
  931. ),
  932. [],
  933. )
  934. self.assertEqual(
  935. list(
  936. Review.objects.using("other")
  937. .filter(object_id=dive.pk)
  938. .values_list("source", flat=True)
  939. ),
  940. [],
  941. )
  942. # Create an author through the generic interface
  943. dive.reviews.create(source="Python Daily")
  944. self.assertEqual(
  945. list(
  946. Review.objects.using("default")
  947. .filter(object_id=dive.pk)
  948. .values_list("source", flat=True)
  949. ),
  950. [],
  951. )
  952. self.assertEqual(
  953. list(
  954. Review.objects.using("other")
  955. .filter(object_id=dive.pk)
  956. .values_list("source", flat=True)
  957. ),
  958. ["Python Daily"],
  959. )
  960. def test_generic_key_cross_database_protection(self):
  961. """
  962. Operations that involve sharing generic key objects across databases
  963. raise an error.
  964. """
  965. # Create a book and author on the default database
  966. pro = Book.objects.create(
  967. title="Pro Django", published=datetime.date(2008, 12, 16)
  968. )
  969. review1 = Review.objects.create(source="Python Monthly", content_object=pro)
  970. # Create a book and author on the other database
  971. dive = Book.objects.using("other").create(
  972. title="Dive into Python", published=datetime.date(2009, 5, 4)
  973. )
  974. Review.objects.using("other").create(
  975. source="Python Weekly", content_object=dive
  976. )
  977. # Set a foreign key with an object from a different database
  978. msg = (
  979. 'Cannot assign "<ContentType: multiple_database | book>": the '
  980. "current database router prevents this relation."
  981. )
  982. with self.assertRaisesMessage(ValueError, msg):
  983. review1.content_object = dive
  984. # Add to a foreign key set with an object from a different database
  985. msg = (
  986. "<Review: Python Monthly> instance isn't saved. "
  987. "Use bulk=False or save the object first."
  988. )
  989. with self.assertRaisesMessage(ValueError, msg):
  990. with transaction.atomic(using="other"):
  991. dive.reviews.add(review1)
  992. # BUT! if you assign a FK object when the base object hasn't
  993. # been saved yet, you implicitly assign the database for the
  994. # base object.
  995. review3 = Review(source="Python Daily")
  996. # initially, no db assigned
  997. self.assertIsNone(review3._state.db)
  998. # Dive comes from 'other', so review3 is set to use 'other'...
  999. review3.content_object = dive
  1000. self.assertEqual(review3._state.db, "other")
  1001. # ... but it isn't saved yet
  1002. self.assertEqual(
  1003. list(
  1004. Review.objects.using("default")
  1005. .filter(object_id=pro.pk)
  1006. .values_list("source", flat=True)
  1007. ),
  1008. ["Python Monthly"],
  1009. )
  1010. self.assertEqual(
  1011. list(
  1012. Review.objects.using("other")
  1013. .filter(object_id=dive.pk)
  1014. .values_list("source", flat=True)
  1015. ),
  1016. ["Python Weekly"],
  1017. )
  1018. # When saved, John goes to 'other'
  1019. review3.save()
  1020. self.assertEqual(
  1021. list(
  1022. Review.objects.using("default")
  1023. .filter(object_id=pro.pk)
  1024. .values_list("source", flat=True)
  1025. ),
  1026. ["Python Monthly"],
  1027. )
  1028. self.assertEqual(
  1029. list(
  1030. Review.objects.using("other")
  1031. .filter(object_id=dive.pk)
  1032. .values_list("source", flat=True)
  1033. ),
  1034. ["Python Daily", "Python Weekly"],
  1035. )
  1036. def test_generic_key_deletion(self):
  1037. """
  1038. Cascaded deletions of Generic Key relations issue queries on the right
  1039. database.
  1040. """
  1041. dive = Book.objects.using("other").create(
  1042. title="Dive into Python", published=datetime.date(2009, 5, 4)
  1043. )
  1044. Review.objects.using("other").create(
  1045. source="Python Weekly", content_object=dive
  1046. )
  1047. # Check the initial state
  1048. self.assertEqual(Book.objects.using("default").count(), 0)
  1049. self.assertEqual(Review.objects.using("default").count(), 0)
  1050. self.assertEqual(Book.objects.using("other").count(), 1)
  1051. self.assertEqual(Review.objects.using("other").count(), 1)
  1052. # Delete the Book object, which will cascade onto the pet
  1053. dive.delete(using="other")
  1054. self.assertEqual(Book.objects.using("default").count(), 0)
  1055. self.assertEqual(Review.objects.using("default").count(), 0)
  1056. # Both the pet and the person have been deleted from the right database
  1057. self.assertEqual(Book.objects.using("other").count(), 0)
  1058. self.assertEqual(Review.objects.using("other").count(), 0)
  1059. def test_ordering(self):
  1060. "get_next_by_XXX commands stick to a single database"
  1061. Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
  1062. dive = Book.objects.using("other").create(
  1063. title="Dive into Python", published=datetime.date(2009, 5, 4)
  1064. )
  1065. learn = Book.objects.using("other").create(
  1066. title="Learning Python", published=datetime.date(2008, 7, 16)
  1067. )
  1068. self.assertEqual(learn.get_next_by_published().title, "Dive into Python")
  1069. self.assertEqual(dive.get_previous_by_published().title, "Learning Python")
  1070. def test_raw(self):
  1071. "test the raw() method across databases"
  1072. dive = Book.objects.using("other").create(
  1073. title="Dive into Python", published=datetime.date(2009, 5, 4)
  1074. )
  1075. val = Book.objects.db_manager("other").raw(
  1076. "SELECT id FROM multiple_database_book"
  1077. )
  1078. self.assertQuerysetEqual(val, [dive.pk], attrgetter("pk"))
  1079. val = Book.objects.raw("SELECT id FROM multiple_database_book").using("other")
  1080. self.assertQuerysetEqual(val, [dive.pk], attrgetter("pk"))
  1081. def test_select_related(self):
  1082. """
  1083. Database assignment is retained if an object is retrieved with
  1084. select_related().
  1085. """
  1086. # Create a book and author on the other database
  1087. mark = Person.objects.using("other").create(name="Mark Pilgrim")
  1088. Book.objects.using("other").create(
  1089. title="Dive into Python",
  1090. published=datetime.date(2009, 5, 4),
  1091. editor=mark,
  1092. )
  1093. # Retrieve the Person using select_related()
  1094. book = (
  1095. Book.objects.using("other")
  1096. .select_related("editor")
  1097. .get(title="Dive into Python")
  1098. )
  1099. # The editor instance should have a db state
  1100. self.assertEqual(book.editor._state.db, "other")
  1101. def test_subquery(self):
  1102. """Make sure as_sql works with subqueries and primary/replica."""
  1103. sub = Person.objects.using("other").filter(name="fff")
  1104. qs = Book.objects.filter(editor__in=sub)
  1105. # When you call __str__ on the query object, it doesn't know about using
  1106. # so it falls back to the default. If the subquery explicitly uses a
  1107. # different database, an error should be raised.
  1108. msg = (
  1109. "Subqueries aren't allowed across different databases. Force the "
  1110. "inner query to be evaluated using `list(inner_query)`."
  1111. )
  1112. with self.assertRaisesMessage(ValueError, msg):
  1113. str(qs.query)
  1114. # Evaluating the query shouldn't work, either
  1115. with self.assertRaisesMessage(ValueError, msg):
  1116. for obj in qs:
  1117. pass
  1118. def test_related_manager(self):
  1119. "Related managers return managers, not querysets"
  1120. mark = Person.objects.using("other").create(name="Mark Pilgrim")
  1121. # extra_arg is removed by the BookManager's implementation of
  1122. # create(); but the BookManager's implementation won't get called
  1123. # unless edited returns a Manager, not a queryset
  1124. mark.book_set.create(
  1125. title="Dive into Python",
  1126. published=datetime.date(2009, 5, 4),
  1127. extra_arg=True,
  1128. )
  1129. mark.book_set.get_or_create(
  1130. title="Dive into Python",
  1131. published=datetime.date(2009, 5, 4),
  1132. extra_arg=True,
  1133. )
  1134. mark.edited.create(
  1135. title="Dive into Water", published=datetime.date(2009, 5, 4), extra_arg=True
  1136. )
  1137. mark.edited.get_or_create(
  1138. title="Dive into Water", published=datetime.date(2009, 5, 4), extra_arg=True
  1139. )
  1140. class ConnectionRouterTestCase(SimpleTestCase):
  1141. @override_settings(
  1142. DATABASE_ROUTERS=[
  1143. "multiple_database.tests.TestRouter",
  1144. "multiple_database.tests.WriteRouter",
  1145. ]
  1146. )
  1147. def test_router_init_default(self):
  1148. connection_router = ConnectionRouter()
  1149. self.assertEqual(
  1150. [r.__class__.__name__ for r in connection_router.routers],
  1151. ["TestRouter", "WriteRouter"],
  1152. )
  1153. def test_router_init_arg(self):
  1154. connection_router = ConnectionRouter(
  1155. [
  1156. "multiple_database.tests.TestRouter",
  1157. "multiple_database.tests.WriteRouter",
  1158. ]
  1159. )
  1160. self.assertEqual(
  1161. [r.__class__.__name__ for r in connection_router.routers],
  1162. ["TestRouter", "WriteRouter"],
  1163. )
  1164. # Init with instances instead of strings
  1165. connection_router = ConnectionRouter([TestRouter(), WriteRouter()])
  1166. self.assertEqual(
  1167. [r.__class__.__name__ for r in connection_router.routers],
  1168. ["TestRouter", "WriteRouter"],
  1169. )
  1170. # Make the 'other' database appear to be a replica of the 'default'
  1171. @override_settings(DATABASE_ROUTERS=[TestRouter()])
  1172. class RouterTestCase(TestCase):
  1173. databases = {"default", "other"}
  1174. def test_db_selection(self):
  1175. "Querysets obey the router for db suggestions"
  1176. self.assertEqual(Book.objects.db, "other")
  1177. self.assertEqual(Book.objects.all().db, "other")
  1178. self.assertEqual(Book.objects.using("default").db, "default")
  1179. self.assertEqual(Book.objects.db_manager("default").db, "default")
  1180. self.assertEqual(Book.objects.db_manager("default").all().db, "default")
  1181. def test_migrate_selection(self):
  1182. "Synchronization behavior is predictable"
  1183. self.assertTrue(router.allow_migrate_model("default", User))
  1184. self.assertTrue(router.allow_migrate_model("default", Book))
  1185. self.assertTrue(router.allow_migrate_model("other", User))
  1186. self.assertTrue(router.allow_migrate_model("other", Book))
  1187. with override_settings(DATABASE_ROUTERS=[TestRouter(), AuthRouter()]):
  1188. # Add the auth router to the chain. TestRouter is a universal
  1189. # synchronizer, so it should have no effect.
  1190. self.assertTrue(router.allow_migrate_model("default", User))
  1191. self.assertTrue(router.allow_migrate_model("default", Book))
  1192. self.assertTrue(router.allow_migrate_model("other", User))
  1193. self.assertTrue(router.allow_migrate_model("other", Book))
  1194. with override_settings(DATABASE_ROUTERS=[AuthRouter(), TestRouter()]):
  1195. # Now check what happens if the router order is reversed.
  1196. self.assertFalse(router.allow_migrate_model("default", User))
  1197. self.assertTrue(router.allow_migrate_model("default", Book))
  1198. self.assertTrue(router.allow_migrate_model("other", User))
  1199. self.assertTrue(router.allow_migrate_model("other", Book))
  1200. def test_partial_router(self):
  1201. "A router can choose to implement a subset of methods"
  1202. dive = Book.objects.using("other").create(
  1203. title="Dive into Python", published=datetime.date(2009, 5, 4)
  1204. )
  1205. # First check the baseline behavior.
  1206. self.assertEqual(router.db_for_read(User), "other")
  1207. self.assertEqual(router.db_for_read(Book), "other")
  1208. self.assertEqual(router.db_for_write(User), "default")
  1209. self.assertEqual(router.db_for_write(Book), "default")
  1210. self.assertTrue(router.allow_relation(dive, dive))
  1211. self.assertTrue(router.allow_migrate_model("default", User))
  1212. self.assertTrue(router.allow_migrate_model("default", Book))
  1213. with override_settings(
  1214. DATABASE_ROUTERS=[WriteRouter(), AuthRouter(), TestRouter()]
  1215. ):
  1216. self.assertEqual(router.db_for_read(User), "default")
  1217. self.assertEqual(router.db_for_read(Book), "other")
  1218. self.assertEqual(router.db_for_write(User), "writer")
  1219. self.assertEqual(router.db_for_write(Book), "writer")
  1220. self.assertTrue(router.allow_relation(dive, dive))
  1221. self.assertFalse(router.allow_migrate_model("default", User))
  1222. self.assertTrue(router.allow_migrate_model("default", Book))
  1223. def test_database_routing(self):
  1224. marty = Person.objects.using("default").create(name="Marty Alchin")
  1225. pro = Book.objects.using("default").create(
  1226. title="Pro Django",
  1227. published=datetime.date(2008, 12, 16),
  1228. editor=marty,
  1229. )
  1230. pro.authors.set([marty])
  1231. # Create a book and author on the other database
  1232. Book.objects.using("other").create(
  1233. title="Dive into Python", published=datetime.date(2009, 5, 4)
  1234. )
  1235. # An update query will be routed to the default database
  1236. Book.objects.filter(title="Pro Django").update(pages=200)
  1237. with self.assertRaises(Book.DoesNotExist):
  1238. # By default, the get query will be directed to 'other'
  1239. Book.objects.get(title="Pro Django")
  1240. # But the same query issued explicitly at a database will work.
  1241. pro = Book.objects.using("default").get(title="Pro Django")
  1242. # The update worked.
  1243. self.assertEqual(pro.pages, 200)
  1244. # An update query with an explicit using clause will be routed
  1245. # to the requested database.
  1246. Book.objects.using("other").filter(title="Dive into Python").update(pages=300)
  1247. self.assertEqual(Book.objects.get(title="Dive into Python").pages, 300)
  1248. # Related object queries stick to the same database
  1249. # as the original object, regardless of the router
  1250. self.assertEqual(
  1251. list(pro.authors.values_list("name", flat=True)), ["Marty Alchin"]
  1252. )
  1253. self.assertEqual(pro.editor.name, "Marty Alchin")
  1254. # get_or_create is a special case. The get needs to be targeted at
  1255. # the write database in order to avoid potential transaction
  1256. # consistency problems
  1257. book, created = Book.objects.get_or_create(title="Pro Django")
  1258. self.assertFalse(created)
  1259. book, created = Book.objects.get_or_create(
  1260. title="Dive Into Python", defaults={"published": datetime.date(2009, 5, 4)}
  1261. )
  1262. self.assertTrue(created)
  1263. # Check the head count of objects
  1264. self.assertEqual(Book.objects.using("default").count(), 2)
  1265. self.assertEqual(Book.objects.using("other").count(), 1)
  1266. # If a database isn't specified, the read database is used
  1267. self.assertEqual(Book.objects.count(), 1)
  1268. # A delete query will also be routed to the default database
  1269. Book.objects.filter(pages__gt=150).delete()
  1270. # The default database has lost the book.
  1271. self.assertEqual(Book.objects.using("default").count(), 1)
  1272. self.assertEqual(Book.objects.using("other").count(), 1)
  1273. def test_invalid_set_foreign_key_assignment(self):
  1274. marty = Person.objects.using("default").create(name="Marty Alchin")
  1275. dive = Book.objects.using("other").create(
  1276. title="Dive into Python",
  1277. published=datetime.date(2009, 5, 4),
  1278. )
  1279. # Set a foreign key set with an object from a different database
  1280. msg = (
  1281. "<Book: Dive into Python> instance isn't saved. Use bulk=False or save the "
  1282. "object first."
  1283. )
  1284. with self.assertRaisesMessage(ValueError, msg):
  1285. marty.edited.set([dive])
  1286. def test_foreign_key_cross_database_protection(self):
  1287. "Foreign keys can cross databases if they two databases have a common source"
  1288. # Create a book and author on the default database
  1289. pro = Book.objects.using("default").create(
  1290. title="Pro Django", published=datetime.date(2008, 12, 16)
  1291. )
  1292. marty = Person.objects.using("default").create(name="Marty Alchin")
  1293. # Create a book and author on the other database
  1294. dive = Book.objects.using("other").create(
  1295. title="Dive into Python", published=datetime.date(2009, 5, 4)
  1296. )
  1297. mark = Person.objects.using("other").create(name="Mark Pilgrim")
  1298. # Set a foreign key with an object from a different database
  1299. dive.editor = marty
  1300. # Database assignments of original objects haven't changed...
  1301. self.assertEqual(marty._state.db, "default")
  1302. self.assertEqual(pro._state.db, "default")
  1303. self.assertEqual(dive._state.db, "other")
  1304. self.assertEqual(mark._state.db, "other")
  1305. # ... but they will when the affected object is saved.
  1306. dive.save()
  1307. self.assertEqual(dive._state.db, "default")
  1308. # ...and the source database now has a copy of any object saved
  1309. Book.objects.using("default").get(title="Dive into Python").delete()
  1310. # This isn't a real primary/replica database, so restore the original from other
  1311. dive = Book.objects.using("other").get(title="Dive into Python")
  1312. self.assertEqual(dive._state.db, "other")
  1313. # Set a foreign key set with an object from a different database
  1314. marty.edited.set([pro, dive], bulk=False)
  1315. # Assignment implies a save, so database assignments of original
  1316. # objects have changed...
  1317. self.assertEqual(marty._state.db, "default")
  1318. self.assertEqual(pro._state.db, "default")
  1319. self.assertEqual(dive._state.db, "default")
  1320. self.assertEqual(mark._state.db, "other")
  1321. # ...and the source database now has a copy of any object saved
  1322. Book.objects.using("default").get(title="Dive into Python").delete()
  1323. # This isn't a real primary/replica database, so restore the original from other
  1324. dive = Book.objects.using("other").get(title="Dive into Python")
  1325. self.assertEqual(dive._state.db, "other")
  1326. # Add to a foreign key set with an object from a different database
  1327. marty.edited.add(dive, bulk=False)
  1328. # Add implies a save, so database assignments of original objects have
  1329. # changed...
  1330. self.assertEqual(marty._state.db, "default")
  1331. self.assertEqual(pro._state.db, "default")
  1332. self.assertEqual(dive._state.db, "default")
  1333. self.assertEqual(mark._state.db, "other")
  1334. # ...and the source database now has a copy of any object saved
  1335. Book.objects.using("default").get(title="Dive into Python").delete()
  1336. # This isn't a real primary/replica database, so restore the original from other
  1337. dive = Book.objects.using("other").get(title="Dive into Python")
  1338. # If you assign a FK object when the base object hasn't
  1339. # been saved yet, you implicitly assign the database for the
  1340. # base object.
  1341. chris = Person(name="Chris Mills")
  1342. html5 = Book(title="Dive into HTML5", published=datetime.date(2010, 3, 15))
  1343. # initially, no db assigned
  1344. self.assertIsNone(chris._state.db)
  1345. self.assertIsNone(html5._state.db)
  1346. # old object comes from 'other', so the new object is set to use the
  1347. # source of 'other'...
  1348. self.assertEqual(dive._state.db, "other")
  1349. chris.save()
  1350. dive.editor = chris
  1351. html5.editor = mark
  1352. self.assertEqual(dive._state.db, "other")
  1353. self.assertEqual(mark._state.db, "other")
  1354. self.assertEqual(chris._state.db, "default")
  1355. self.assertEqual(html5._state.db, "default")
  1356. # This also works if you assign the FK in the constructor
  1357. water = Book(
  1358. title="Dive into Water", published=datetime.date(2001, 1, 1), editor=mark
  1359. )
  1360. self.assertEqual(water._state.db, "default")
  1361. # For the remainder of this test, create a copy of 'mark' in the
  1362. # 'default' database to prevent integrity errors on backends that
  1363. # don't defer constraints checks until the end of the transaction
  1364. mark.save(using="default")
  1365. # This moved 'mark' in the 'default' database, move it back in 'other'
  1366. mark.save(using="other")
  1367. self.assertEqual(mark._state.db, "other")
  1368. # If you create an object through a FK relation, it will be
  1369. # written to the write database, even if the original object
  1370. # was on the read database
  1371. cheesecake = mark.edited.create(
  1372. title="Dive into Cheesecake", published=datetime.date(2010, 3, 15)
  1373. )
  1374. self.assertEqual(cheesecake._state.db, "default")
  1375. # Same goes for get_or_create, regardless of whether getting or creating
  1376. cheesecake, created = mark.edited.get_or_create(
  1377. title="Dive into Cheesecake",
  1378. published=datetime.date(2010, 3, 15),
  1379. )
  1380. self.assertEqual(cheesecake._state.db, "default")
  1381. puddles, created = mark.edited.get_or_create(
  1382. title="Dive into Puddles", published=datetime.date(2010, 3, 15)
  1383. )
  1384. self.assertEqual(puddles._state.db, "default")
  1385. def test_m2m_cross_database_protection(self):
  1386. "M2M relations can cross databases if the database share a source"
  1387. # Create books and authors on the inverse to the usual database
  1388. pro = Book.objects.using("other").create(
  1389. pk=1, title="Pro Django", published=datetime.date(2008, 12, 16)
  1390. )
  1391. marty = Person.objects.using("other").create(pk=1, name="Marty Alchin")
  1392. dive = Book.objects.using("default").create(
  1393. pk=2, title="Dive into Python", published=datetime.date(2009, 5, 4)
  1394. )
  1395. mark = Person.objects.using("default").create(pk=2, name="Mark Pilgrim")
  1396. # Now save back onto the usual database.
  1397. # This simulates primary/replica - the objects exist on both database,
  1398. # but the _state.db is as it is for all other tests.
  1399. pro.save(using="default")
  1400. marty.save(using="default")
  1401. dive.save(using="other")
  1402. mark.save(using="other")
  1403. # We have 2 of both types of object on both databases
  1404. self.assertEqual(Book.objects.using("default").count(), 2)
  1405. self.assertEqual(Book.objects.using("other").count(), 2)
  1406. self.assertEqual(Person.objects.using("default").count(), 2)
  1407. self.assertEqual(Person.objects.using("other").count(), 2)
  1408. # Set a m2m set with an object from a different database
  1409. marty.book_set.set([pro, dive])
  1410. # Database assignments don't change
  1411. self.assertEqual(marty._state.db, "default")
  1412. self.assertEqual(pro._state.db, "default")
  1413. self.assertEqual(dive._state.db, "other")
  1414. self.assertEqual(mark._state.db, "other")
  1415. # All m2m relations should be saved on the default database
  1416. self.assertEqual(Book.authors.through.objects.using("default").count(), 2)
  1417. self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
  1418. # Reset relations
  1419. Book.authors.through.objects.using("default").delete()
  1420. # Add to an m2m with an object from a different database
  1421. marty.book_set.add(dive)
  1422. # Database assignments don't change
  1423. self.assertEqual(marty._state.db, "default")
  1424. self.assertEqual(pro._state.db, "default")
  1425. self.assertEqual(dive._state.db, "other")
  1426. self.assertEqual(mark._state.db, "other")
  1427. # All m2m relations should be saved on the default database
  1428. self.assertEqual(Book.authors.through.objects.using("default").count(), 1)
  1429. self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
  1430. # Reset relations
  1431. Book.authors.through.objects.using("default").delete()
  1432. # Set a reverse m2m with an object from a different database
  1433. dive.authors.set([mark, marty])
  1434. # Database assignments don't change
  1435. self.assertEqual(marty._state.db, "default")
  1436. self.assertEqual(pro._state.db, "default")
  1437. self.assertEqual(dive._state.db, "other")
  1438. self.assertEqual(mark._state.db, "other")
  1439. # All m2m relations should be saved on the default database
  1440. self.assertEqual(Book.authors.through.objects.using("default").count(), 2)
  1441. self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
  1442. # Reset relations
  1443. Book.authors.through.objects.using("default").delete()
  1444. self.assertEqual(Book.authors.through.objects.using("default").count(), 0)
  1445. self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
  1446. # Add to a reverse m2m with an object from a different database
  1447. dive.authors.add(marty)
  1448. # Database assignments don't change
  1449. self.assertEqual(marty._state.db, "default")
  1450. self.assertEqual(pro._state.db, "default")
  1451. self.assertEqual(dive._state.db, "other")
  1452. self.assertEqual(mark._state.db, "other")
  1453. # All m2m relations should be saved on the default database
  1454. self.assertEqual(Book.authors.through.objects.using("default").count(), 1)
  1455. self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
  1456. # If you create an object through a M2M relation, it will be
  1457. # written to the write database, even if the original object
  1458. # was on the read database
  1459. alice = dive.authors.create(name="Alice", pk=3)
  1460. self.assertEqual(alice._state.db, "default")
  1461. # Same goes for get_or_create, regardless of whether getting or creating
  1462. alice, created = dive.authors.get_or_create(name="Alice")
  1463. self.assertEqual(alice._state.db, "default")
  1464. bob, created = dive.authors.get_or_create(name="Bob", defaults={"pk": 4})
  1465. self.assertEqual(bob._state.db, "default")
  1466. def test_o2o_cross_database_protection(self):
  1467. "Operations that involve sharing FK objects across databases raise an error"
  1468. # Create a user and profile on the default database
  1469. alice = User.objects.db_manager("default").create_user(
  1470. "alice", "alice@example.com"
  1471. )
  1472. # Create a user and profile on the other database
  1473. bob = User.objects.db_manager("other").create_user("bob", "bob@example.com")
  1474. # Set a one-to-one relation with an object from a different database
  1475. alice_profile = UserProfile.objects.create(user=alice, flavor="chocolate")
  1476. bob.userprofile = alice_profile
  1477. # Database assignments of original objects haven't changed...
  1478. self.assertEqual(alice._state.db, "default")
  1479. self.assertEqual(alice_profile._state.db, "default")
  1480. self.assertEqual(bob._state.db, "other")
  1481. # ... but they will when the affected object is saved.
  1482. bob.save()
  1483. self.assertEqual(bob._state.db, "default")
  1484. def test_generic_key_cross_database_protection(self):
  1485. "Generic Key operations can span databases if they share a source"
  1486. # Create a book and author on the default database
  1487. pro = Book.objects.using("default").create(
  1488. title="Pro Django", published=datetime.date(2008, 12, 16)
  1489. )
  1490. review1 = Review.objects.using("default").create(
  1491. source="Python Monthly", content_object=pro
  1492. )
  1493. # Create a book and author on the other database
  1494. dive = Book.objects.using("other").create(
  1495. title="Dive into Python", published=datetime.date(2009, 5, 4)
  1496. )
  1497. review2 = Review.objects.using("other").create(
  1498. source="Python Weekly", content_object=dive
  1499. )
  1500. # Set a generic foreign key with an object from a different database
  1501. review1.content_object = dive
  1502. # Database assignments of original objects haven't changed...
  1503. self.assertEqual(pro._state.db, "default")
  1504. self.assertEqual(review1._state.db, "default")
  1505. self.assertEqual(dive._state.db, "other")
  1506. self.assertEqual(review2._state.db, "other")
  1507. # ... but they will when the affected object is saved.
  1508. dive.save()
  1509. self.assertEqual(review1._state.db, "default")
  1510. self.assertEqual(dive._state.db, "default")
  1511. # ...and the source database now has a copy of any object saved
  1512. Book.objects.using("default").get(title="Dive into Python").delete()
  1513. # This isn't a real primary/replica database, so restore the original from other
  1514. dive = Book.objects.using("other").get(title="Dive into Python")
  1515. self.assertEqual(dive._state.db, "other")
  1516. # Add to a generic foreign key set with an object from a different database
  1517. dive.reviews.add(review1)
  1518. # Database assignments of original objects haven't changed...
  1519. self.assertEqual(pro._state.db, "default")
  1520. self.assertEqual(review1._state.db, "default")
  1521. self.assertEqual(dive._state.db, "other")
  1522. self.assertEqual(review2._state.db, "other")
  1523. # ... but they will when the affected object is saved.
  1524. dive.save()
  1525. self.assertEqual(dive._state.db, "default")
  1526. # ...and the source database now has a copy of any object saved
  1527. Book.objects.using("default").get(title="Dive into Python").delete()
  1528. # BUT! if you assign a FK object when the base object hasn't
  1529. # been saved yet, you implicitly assign the database for the
  1530. # base object.
  1531. review3 = Review(source="Python Daily")
  1532. # initially, no db assigned
  1533. self.assertIsNone(review3._state.db)
  1534. # Dive comes from 'other', so review3 is set to use the source of 'other'...
  1535. review3.content_object = dive
  1536. self.assertEqual(review3._state.db, "default")
  1537. # If you create an object through a M2M relation, it will be
  1538. # written to the write database, even if the original object
  1539. # was on the read database
  1540. dive = Book.objects.using("other").get(title="Dive into Python")
  1541. nyt = dive.reviews.create(source="New York Times", content_object=dive)
  1542. self.assertEqual(nyt._state.db, "default")
  1543. def test_m2m_managers(self):
  1544. "M2M relations are represented by managers, and can be controlled like managers"
  1545. pro = Book.objects.using("other").create(
  1546. pk=1, title="Pro Django", published=datetime.date(2008, 12, 16)
  1547. )
  1548. marty = Person.objects.using("other").create(pk=1, name="Marty Alchin")
  1549. self.assertEqual(pro.authors.db, "other")
  1550. self.assertEqual(pro.authors.db_manager("default").db, "default")
  1551. self.assertEqual(pro.authors.db_manager("default").all().db, "default")
  1552. self.assertEqual(marty.book_set.db, "other")
  1553. self.assertEqual(marty.book_set.db_manager("default").db, "default")
  1554. self.assertEqual(marty.book_set.db_manager("default").all().db, "default")
  1555. def test_foreign_key_managers(self):
  1556. """
  1557. FK reverse relations are represented by managers, and can be controlled
  1558. like managers.
  1559. """
  1560. marty = Person.objects.using("other").create(pk=1, name="Marty Alchin")
  1561. Book.objects.using("other").create(
  1562. pk=1,
  1563. title="Pro Django",
  1564. published=datetime.date(2008, 12, 16),
  1565. editor=marty,
  1566. )
  1567. self.assertEqual(marty.edited.db, "other")
  1568. self.assertEqual(marty.edited.db_manager("default").db, "default")
  1569. self.assertEqual(marty.edited.db_manager("default").all().db, "default")
  1570. def test_generic_key_managers(self):
  1571. """
  1572. Generic key relations are represented by managers, and can be
  1573. controlled like managers.
  1574. """
  1575. pro = Book.objects.using("other").create(
  1576. title="Pro Django", published=datetime.date(2008, 12, 16)
  1577. )
  1578. Review.objects.using("other").create(
  1579. source="Python Monthly", content_object=pro
  1580. )
  1581. self.assertEqual(pro.reviews.db, "other")
  1582. self.assertEqual(pro.reviews.db_manager("default").db, "default")
  1583. self.assertEqual(pro.reviews.db_manager("default").all().db, "default")
  1584. def test_subquery(self):
  1585. """Make sure as_sql works with subqueries and primary/replica."""
  1586. # Create a book and author on the other database
  1587. mark = Person.objects.using("other").create(name="Mark Pilgrim")
  1588. Book.objects.using("other").create(
  1589. title="Dive into Python",
  1590. published=datetime.date(2009, 5, 4),
  1591. editor=mark,
  1592. )
  1593. sub = Person.objects.filter(name="Mark Pilgrim")
  1594. qs = Book.objects.filter(editor__in=sub)
  1595. # When you call __str__ on the query object, it doesn't know about using
  1596. # so it falls back to the default. Don't let routing instructions
  1597. # force the subquery to an incompatible database.
  1598. str(qs.query)
  1599. # If you evaluate the query, it should work, running on 'other'
  1600. self.assertEqual(list(qs.values_list("title", flat=True)), ["Dive into Python"])
  1601. def test_deferred_models(self):
  1602. mark_def = Person.objects.using("default").create(name="Mark Pilgrim")
  1603. mark_other = Person.objects.using("other").create(name="Mark Pilgrim")
  1604. orig_b = Book.objects.using("other").create(
  1605. title="Dive into Python",
  1606. published=datetime.date(2009, 5, 4),
  1607. editor=mark_other,
  1608. )
  1609. b = Book.objects.using("other").only("title").get(pk=orig_b.pk)
  1610. self.assertEqual(b.published, datetime.date(2009, 5, 4))
  1611. b = Book.objects.using("other").only("title").get(pk=orig_b.pk)
  1612. b.editor = mark_def
  1613. b.save(using="default")
  1614. self.assertEqual(
  1615. Book.objects.using("default").get(pk=b.pk).published,
  1616. datetime.date(2009, 5, 4),
  1617. )
  1618. @override_settings(DATABASE_ROUTERS=[AuthRouter()])
  1619. class AuthTestCase(TestCase):
  1620. databases = {"default", "other"}
  1621. def test_auth_manager(self):
  1622. "The methods on the auth manager obey database hints"
  1623. # Create one user using default allocation policy
  1624. User.objects.create_user("alice", "alice@example.com")
  1625. # Create another user, explicitly specifying the database
  1626. User.objects.db_manager("default").create_user("bob", "bob@example.com")
  1627. # The second user only exists on the other database
  1628. alice = User.objects.using("other").get(username="alice")
  1629. self.assertEqual(alice.username, "alice")
  1630. self.assertEqual(alice._state.db, "other")
  1631. with self.assertRaises(User.DoesNotExist):
  1632. User.objects.using("default").get(username="alice")
  1633. # The second user only exists on the default database
  1634. bob = User.objects.using("default").get(username="bob")
  1635. self.assertEqual(bob.username, "bob")
  1636. self.assertEqual(bob._state.db, "default")
  1637. with self.assertRaises(User.DoesNotExist):
  1638. User.objects.using("other").get(username="bob")
  1639. # That is... there is one user on each database
  1640. self.assertEqual(User.objects.using("default").count(), 1)
  1641. self.assertEqual(User.objects.using("other").count(), 1)
  1642. def test_dumpdata(self):
  1643. "dumpdata honors allow_migrate restrictions on the router"
  1644. User.objects.create_user("alice", "alice@example.com")
  1645. User.objects.db_manager("default").create_user("bob", "bob@example.com")
  1646. # dumping the default database doesn't try to include auth because
  1647. # allow_migrate prohibits auth on default
  1648. new_io = StringIO()
  1649. management.call_command(
  1650. "dumpdata", "auth", format="json", database="default", stdout=new_io
  1651. )
  1652. command_output = new_io.getvalue().strip()
  1653. self.assertEqual(command_output, "[]")
  1654. # dumping the other database does include auth
  1655. new_io = StringIO()
  1656. management.call_command(
  1657. "dumpdata", "auth", format="json", database="other", stdout=new_io
  1658. )
  1659. command_output = new_io.getvalue().strip()
  1660. self.assertIn('"email": "alice@example.com"', command_output)
  1661. class AntiPetRouter:
  1662. # A router that only expresses an opinion on migrate,
  1663. # passing pets to the 'other' database
  1664. def allow_migrate(self, db, app_label, model_name=None, **hints):
  1665. if db == "other":
  1666. return model_name == "pet"
  1667. else:
  1668. return model_name != "pet"
  1669. class FixtureTestCase(TestCase):
  1670. databases = {"default", "other"}
  1671. fixtures = ["multidb-common", "multidb"]
  1672. @override_settings(DATABASE_ROUTERS=[AntiPetRouter()])
  1673. def test_fixture_loading(self):
  1674. "Multi-db fixtures are loaded correctly"
  1675. # "Pro Django" exists on the default database, but not on other database
  1676. Book.objects.get(title="Pro Django")
  1677. Book.objects.using("default").get(title="Pro Django")
  1678. with self.assertRaises(Book.DoesNotExist):
  1679. Book.objects.using("other").get(title="Pro Django")
  1680. # "Dive into Python" exists on the default database, but not on other database
  1681. Book.objects.using("other").get(title="Dive into Python")
  1682. with self.assertRaises(Book.DoesNotExist):
  1683. Book.objects.get(title="Dive into Python")
  1684. with self.assertRaises(Book.DoesNotExist):
  1685. Book.objects.using("default").get(title="Dive into Python")
  1686. # "Definitive Guide" exists on the both databases
  1687. Book.objects.get(title="The Definitive Guide to Django")
  1688. Book.objects.using("default").get(title="The Definitive Guide to Django")
  1689. Book.objects.using("other").get(title="The Definitive Guide to Django")
  1690. @override_settings(DATABASE_ROUTERS=[AntiPetRouter()])
  1691. def test_pseudo_empty_fixtures(self):
  1692. """
  1693. A fixture can contain entries, but lead to nothing in the database;
  1694. this shouldn't raise an error (#14068).
  1695. """
  1696. new_io = StringIO()
  1697. management.call_command("loaddata", "pets", stdout=new_io, stderr=new_io)
  1698. command_output = new_io.getvalue().strip()
  1699. # No objects will actually be loaded
  1700. self.assertEqual(
  1701. command_output, "Installed 0 object(s) (of 2) from 1 fixture(s)"
  1702. )
  1703. class PickleQuerySetTestCase(TestCase):
  1704. databases = {"default", "other"}
  1705. def test_pickling(self):
  1706. for db in self.databases:
  1707. Book.objects.using(db).create(
  1708. title="Dive into Python", published=datetime.date(2009, 5, 4)
  1709. )
  1710. qs = Book.objects.all()
  1711. self.assertEqual(qs.db, pickle.loads(pickle.dumps(qs)).db)
  1712. class DatabaseReceiver:
  1713. """
  1714. Used in the tests for the database argument in signals (#13552)
  1715. """
  1716. def __call__(self, signal, sender, **kwargs):
  1717. self._database = kwargs["using"]
  1718. class WriteToOtherRouter:
  1719. """
  1720. A router that sends all writes to the other database.
  1721. """
  1722. def db_for_write(self, model, **hints):
  1723. return "other"
  1724. class SignalTests(TestCase):
  1725. databases = {"default", "other"}
  1726. def override_router(self):
  1727. return override_settings(DATABASE_ROUTERS=[WriteToOtherRouter()])
  1728. def test_database_arg_save_and_delete(self):
  1729. """
  1730. The pre/post_save signal contains the correct database.
  1731. """
  1732. # Make some signal receivers
  1733. pre_save_receiver = DatabaseReceiver()
  1734. post_save_receiver = DatabaseReceiver()
  1735. pre_delete_receiver = DatabaseReceiver()
  1736. post_delete_receiver = DatabaseReceiver()
  1737. # Make model and connect receivers
  1738. signals.pre_save.connect(sender=Person, receiver=pre_save_receiver)
  1739. signals.post_save.connect(sender=Person, receiver=post_save_receiver)
  1740. signals.pre_delete.connect(sender=Person, receiver=pre_delete_receiver)
  1741. signals.post_delete.connect(sender=Person, receiver=post_delete_receiver)
  1742. p = Person.objects.create(name="Darth Vader")
  1743. # Save and test receivers got calls
  1744. p.save()
  1745. self.assertEqual(pre_save_receiver._database, DEFAULT_DB_ALIAS)
  1746. self.assertEqual(post_save_receiver._database, DEFAULT_DB_ALIAS)
  1747. # Delete, and test
  1748. p.delete()
  1749. self.assertEqual(pre_delete_receiver._database, DEFAULT_DB_ALIAS)
  1750. self.assertEqual(post_delete_receiver._database, DEFAULT_DB_ALIAS)
  1751. # Save again to a different database
  1752. p.save(using="other")
  1753. self.assertEqual(pre_save_receiver._database, "other")
  1754. self.assertEqual(post_save_receiver._database, "other")
  1755. # Delete, and test
  1756. p.delete(using="other")
  1757. self.assertEqual(pre_delete_receiver._database, "other")
  1758. self.assertEqual(post_delete_receiver._database, "other")
  1759. signals.pre_save.disconnect(sender=Person, receiver=pre_save_receiver)
  1760. signals.post_save.disconnect(sender=Person, receiver=post_save_receiver)
  1761. signals.pre_delete.disconnect(sender=Person, receiver=pre_delete_receiver)
  1762. signals.post_delete.disconnect(sender=Person, receiver=post_delete_receiver)
  1763. def test_database_arg_m2m(self):
  1764. """
  1765. The m2m_changed signal has a correct database arg.
  1766. """
  1767. # Make a receiver
  1768. receiver = DatabaseReceiver()
  1769. # Connect it
  1770. signals.m2m_changed.connect(receiver=receiver)
  1771. # Create the models that will be used for the tests
  1772. b = Book.objects.create(
  1773. title="Pro Django", published=datetime.date(2008, 12, 16)
  1774. )
  1775. p = Person.objects.create(name="Marty Alchin")
  1776. # Create a copy of the models on the 'other' database to prevent
  1777. # integrity errors on backends that don't defer constraints checks
  1778. Book.objects.using("other").create(
  1779. pk=b.pk, title=b.title, published=b.published
  1780. )
  1781. Person.objects.using("other").create(pk=p.pk, name=p.name)
  1782. # Test addition
  1783. b.authors.add(p)
  1784. self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
  1785. with self.override_router():
  1786. b.authors.add(p)
  1787. self.assertEqual(receiver._database, "other")
  1788. # Test removal
  1789. b.authors.remove(p)
  1790. self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
  1791. with self.override_router():
  1792. b.authors.remove(p)
  1793. self.assertEqual(receiver._database, "other")
  1794. # Test addition in reverse
  1795. p.book_set.add(b)
  1796. self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
  1797. with self.override_router():
  1798. p.book_set.add(b)
  1799. self.assertEqual(receiver._database, "other")
  1800. # Test clearing
  1801. b.authors.clear()
  1802. self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
  1803. with self.override_router():
  1804. b.authors.clear()
  1805. self.assertEqual(receiver._database, "other")
  1806. class AttributeErrorRouter:
  1807. "A router to test the exception handling of ConnectionRouter"
  1808. def db_for_read(self, model, **hints):
  1809. raise AttributeError
  1810. def db_for_write(self, model, **hints):
  1811. raise AttributeError
  1812. class RouterAttributeErrorTestCase(TestCase):
  1813. databases = {"default", "other"}
  1814. def override_router(self):
  1815. return override_settings(DATABASE_ROUTERS=[AttributeErrorRouter()])
  1816. def test_attribute_error_read(self):
  1817. "The AttributeError from AttributeErrorRouter bubbles up"
  1818. b = Book.objects.create(
  1819. title="Pro Django", published=datetime.date(2008, 12, 16)
  1820. )
  1821. with self.override_router():
  1822. with self.assertRaises(AttributeError):
  1823. Book.objects.get(pk=b.pk)
  1824. def test_attribute_error_save(self):
  1825. "The AttributeError from AttributeErrorRouter bubbles up"
  1826. dive = Book()
  1827. dive.title = "Dive into Python"
  1828. dive.published = datetime.date(2009, 5, 4)
  1829. with self.override_router():
  1830. with self.assertRaises(AttributeError):
  1831. dive.save()
  1832. def test_attribute_error_delete(self):
  1833. "The AttributeError from AttributeErrorRouter bubbles up"
  1834. b = Book.objects.create(
  1835. title="Pro Django", published=datetime.date(2008, 12, 16)
  1836. )
  1837. p = Person.objects.create(name="Marty Alchin")
  1838. b.authors.set([p])
  1839. b.editor = p
  1840. with self.override_router():
  1841. with self.assertRaises(AttributeError):
  1842. b.delete()
  1843. def test_attribute_error_m2m(self):
  1844. "The AttributeError from AttributeErrorRouter bubbles up"
  1845. b = Book.objects.create(
  1846. title="Pro Django", published=datetime.date(2008, 12, 16)
  1847. )
  1848. p = Person.objects.create(name="Marty Alchin")
  1849. with self.override_router():
  1850. with self.assertRaises(AttributeError):
  1851. b.authors.set([p])
  1852. class ModelMetaRouter:
  1853. "A router to ensure model arguments are real model classes"
  1854. def db_for_write(self, model, **hints):
  1855. if not hasattr(model, "_meta"):
  1856. raise ValueError
  1857. @override_settings(DATABASE_ROUTERS=[ModelMetaRouter()])
  1858. class RouterModelArgumentTestCase(TestCase):
  1859. databases = {"default", "other"}
  1860. def test_m2m_collection(self):
  1861. b = Book.objects.create(
  1862. title="Pro Django", published=datetime.date(2008, 12, 16)
  1863. )
  1864. p = Person.objects.create(name="Marty Alchin")
  1865. # test add
  1866. b.authors.add(p)
  1867. # test remove
  1868. b.authors.remove(p)
  1869. # test clear
  1870. b.authors.clear()
  1871. # test setattr
  1872. b.authors.set([p])
  1873. # test M2M collection
  1874. b.delete()
  1875. def test_foreignkey_collection(self):
  1876. person = Person.objects.create(name="Bob")
  1877. Pet.objects.create(owner=person, name="Wart")
  1878. # test related FK collection
  1879. person.delete()
  1880. class SyncOnlyDefaultDatabaseRouter:
  1881. def allow_migrate(self, db, app_label, **hints):
  1882. return db == DEFAULT_DB_ALIAS
  1883. class MigrateTestCase(TestCase):
  1884. # Limit memory usage when calling 'migrate'.
  1885. available_apps = [
  1886. "multiple_database",
  1887. "django.contrib.auth",
  1888. "django.contrib.contenttypes",
  1889. ]
  1890. databases = {"default", "other"}
  1891. def test_migrate_to_other_database(self):
  1892. """Regression test for #16039: migrate with --database option."""
  1893. cts = ContentType.objects.using("other").filter(app_label="multiple_database")
  1894. count = cts.count()
  1895. self.assertGreater(count, 0)
  1896. cts.delete()
  1897. management.call_command(
  1898. "migrate", verbosity=0, interactive=False, database="other"
  1899. )
  1900. self.assertEqual(cts.count(), count)
  1901. def test_migrate_to_other_database_with_router(self):
  1902. """Regression test for #16039: migrate with --database option."""
  1903. cts = ContentType.objects.using("other").filter(app_label="multiple_database")
  1904. cts.delete()
  1905. with override_settings(DATABASE_ROUTERS=[SyncOnlyDefaultDatabaseRouter()]):
  1906. management.call_command(
  1907. "migrate", verbosity=0, interactive=False, database="other"
  1908. )
  1909. self.assertEqual(cts.count(), 0)
  1910. class RouterUsed(Exception):
  1911. WRITE = "write"
  1912. def __init__(self, mode, model, hints):
  1913. self.mode = mode
  1914. self.model = model
  1915. self.hints = hints
  1916. class RouteForWriteTestCase(TestCase):
  1917. databases = {"default", "other"}
  1918. class WriteCheckRouter:
  1919. def db_for_write(self, model, **hints):
  1920. raise RouterUsed(mode=RouterUsed.WRITE, model=model, hints=hints)
  1921. def override_router(self):
  1922. return override_settings(
  1923. DATABASE_ROUTERS=[RouteForWriteTestCase.WriteCheckRouter()]
  1924. )
  1925. def test_fk_delete(self):
  1926. owner = Person.objects.create(name="Someone")
  1927. pet = Pet.objects.create(name="fido", owner=owner)
  1928. with self.assertRaises(RouterUsed) as cm:
  1929. with self.override_router():
  1930. pet.owner.delete()
  1931. e = cm.exception
  1932. self.assertEqual(e.mode, RouterUsed.WRITE)
  1933. self.assertEqual(e.model, Person)
  1934. self.assertEqual(e.hints, {"instance": owner})
  1935. def test_reverse_fk_delete(self):
  1936. owner = Person.objects.create(name="Someone")
  1937. to_del_qs = owner.pet_set.all()
  1938. with self.assertRaises(RouterUsed) as cm:
  1939. with self.override_router():
  1940. to_del_qs.delete()
  1941. e = cm.exception
  1942. self.assertEqual(e.mode, RouterUsed.WRITE)
  1943. self.assertEqual(e.model, Pet)
  1944. self.assertEqual(e.hints, {"instance": owner})
  1945. def test_reverse_fk_get_or_create(self):
  1946. owner = Person.objects.create(name="Someone")
  1947. with self.assertRaises(RouterUsed) as cm:
  1948. with self.override_router():
  1949. owner.pet_set.get_or_create(name="fido")
  1950. e = cm.exception
  1951. self.assertEqual(e.mode, RouterUsed.WRITE)
  1952. self.assertEqual(e.model, Pet)
  1953. self.assertEqual(e.hints, {"instance": owner})
  1954. def test_reverse_fk_update(self):
  1955. owner = Person.objects.create(name="Someone")
  1956. Pet.objects.create(name="fido", owner=owner)
  1957. with self.assertRaises(RouterUsed) as cm:
  1958. with self.override_router():
  1959. owner.pet_set.update(name="max")
  1960. e = cm.exception
  1961. self.assertEqual(e.mode, RouterUsed.WRITE)
  1962. self.assertEqual(e.model, Pet)
  1963. self.assertEqual(e.hints, {"instance": owner})
  1964. def test_m2m_add(self):
  1965. auth = Person.objects.create(name="Someone")
  1966. book = Book.objects.create(
  1967. title="Pro Django", published=datetime.date(2008, 12, 16)
  1968. )
  1969. with self.assertRaises(RouterUsed) as cm:
  1970. with self.override_router():
  1971. book.authors.add(auth)
  1972. e = cm.exception
  1973. self.assertEqual(e.mode, RouterUsed.WRITE)
  1974. self.assertEqual(e.model, Book.authors.through)
  1975. self.assertEqual(e.hints, {"instance": book})
  1976. def test_m2m_clear(self):
  1977. auth = Person.objects.create(name="Someone")
  1978. book = Book.objects.create(
  1979. title="Pro Django", published=datetime.date(2008, 12, 16)
  1980. )
  1981. book.authors.add(auth)
  1982. with self.assertRaises(RouterUsed) as cm:
  1983. with self.override_router():
  1984. book.authors.clear()
  1985. e = cm.exception
  1986. self.assertEqual(e.mode, RouterUsed.WRITE)
  1987. self.assertEqual(e.model, Book.authors.through)
  1988. self.assertEqual(e.hints, {"instance": book})
  1989. def test_m2m_delete(self):
  1990. auth = Person.objects.create(name="Someone")
  1991. book = Book.objects.create(
  1992. title="Pro Django", published=datetime.date(2008, 12, 16)
  1993. )
  1994. book.authors.add(auth)
  1995. with self.assertRaises(RouterUsed) as cm:
  1996. with self.override_router():
  1997. book.authors.all().delete()
  1998. e = cm.exception
  1999. self.assertEqual(e.mode, RouterUsed.WRITE)
  2000. self.assertEqual(e.model, Person)
  2001. self.assertEqual(e.hints, {"instance": book})
  2002. def test_m2m_get_or_create(self):
  2003. Person.objects.create(name="Someone")
  2004. book = Book.objects.create(
  2005. title="Pro Django", published=datetime.date(2008, 12, 16)
  2006. )
  2007. with self.assertRaises(RouterUsed) as cm:
  2008. with self.override_router():
  2009. book.authors.get_or_create(name="Someone else")
  2010. e = cm.exception
  2011. self.assertEqual(e.mode, RouterUsed.WRITE)
  2012. self.assertEqual(e.model, Book)
  2013. self.assertEqual(e.hints, {"instance": book})
  2014. def test_m2m_remove(self):
  2015. auth = Person.objects.create(name="Someone")
  2016. book = Book.objects.create(
  2017. title="Pro Django", published=datetime.date(2008, 12, 16)
  2018. )
  2019. book.authors.add(auth)
  2020. with self.assertRaises(RouterUsed) as cm:
  2021. with self.override_router():
  2022. book.authors.remove(auth)
  2023. e = cm.exception
  2024. self.assertEqual(e.mode, RouterUsed.WRITE)
  2025. self.assertEqual(e.model, Book.authors.through)
  2026. self.assertEqual(e.hints, {"instance": book})
  2027. def test_m2m_update(self):
  2028. auth = Person.objects.create(name="Someone")
  2029. book = Book.objects.create(
  2030. title="Pro Django", published=datetime.date(2008, 12, 16)
  2031. )
  2032. book.authors.add(auth)
  2033. with self.assertRaises(RouterUsed) as cm:
  2034. with self.override_router():
  2035. book.authors.update(name="Different")
  2036. e = cm.exception
  2037. self.assertEqual(e.mode, RouterUsed.WRITE)
  2038. self.assertEqual(e.model, Person)
  2039. self.assertEqual(e.hints, {"instance": book})
  2040. def test_reverse_m2m_add(self):
  2041. auth = Person.objects.create(name="Someone")
  2042. book = Book.objects.create(
  2043. title="Pro Django", published=datetime.date(2008, 12, 16)
  2044. )
  2045. with self.assertRaises(RouterUsed) as cm:
  2046. with self.override_router():
  2047. auth.book_set.add(book)
  2048. e = cm.exception
  2049. self.assertEqual(e.mode, RouterUsed.WRITE)
  2050. self.assertEqual(e.model, Book.authors.through)
  2051. self.assertEqual(e.hints, {"instance": auth})
  2052. def test_reverse_m2m_clear(self):
  2053. auth = Person.objects.create(name="Someone")
  2054. book = Book.objects.create(
  2055. title="Pro Django", published=datetime.date(2008, 12, 16)
  2056. )
  2057. book.authors.add(auth)
  2058. with self.assertRaises(RouterUsed) as cm:
  2059. with self.override_router():
  2060. auth.book_set.clear()
  2061. e = cm.exception
  2062. self.assertEqual(e.mode, RouterUsed.WRITE)
  2063. self.assertEqual(e.model, Book.authors.through)
  2064. self.assertEqual(e.hints, {"instance": auth})
  2065. def test_reverse_m2m_delete(self):
  2066. auth = Person.objects.create(name="Someone")
  2067. book = Book.objects.create(
  2068. title="Pro Django", published=datetime.date(2008, 12, 16)
  2069. )
  2070. book.authors.add(auth)
  2071. with self.assertRaises(RouterUsed) as cm:
  2072. with self.override_router():
  2073. auth.book_set.all().delete()
  2074. e = cm.exception
  2075. self.assertEqual(e.mode, RouterUsed.WRITE)
  2076. self.assertEqual(e.model, Book)
  2077. self.assertEqual(e.hints, {"instance": auth})
  2078. def test_reverse_m2m_get_or_create(self):
  2079. auth = Person.objects.create(name="Someone")
  2080. Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
  2081. with self.assertRaises(RouterUsed) as cm:
  2082. with self.override_router():
  2083. auth.book_set.get_or_create(
  2084. title="New Book", published=datetime.datetime.now()
  2085. )
  2086. e = cm.exception
  2087. self.assertEqual(e.mode, RouterUsed.WRITE)
  2088. self.assertEqual(e.model, Person)
  2089. self.assertEqual(e.hints, {"instance": auth})
  2090. def test_reverse_m2m_remove(self):
  2091. auth = Person.objects.create(name="Someone")
  2092. book = Book.objects.create(
  2093. title="Pro Django", published=datetime.date(2008, 12, 16)
  2094. )
  2095. book.authors.add(auth)
  2096. with self.assertRaises(RouterUsed) as cm:
  2097. with self.override_router():
  2098. auth.book_set.remove(book)
  2099. e = cm.exception
  2100. self.assertEqual(e.mode, RouterUsed.WRITE)
  2101. self.assertEqual(e.model, Book.authors.through)
  2102. self.assertEqual(e.hints, {"instance": auth})
  2103. def test_reverse_m2m_update(self):
  2104. auth = Person.objects.create(name="Someone")
  2105. book = Book.objects.create(
  2106. title="Pro Django", published=datetime.date(2008, 12, 16)
  2107. )
  2108. book.authors.add(auth)
  2109. with self.assertRaises(RouterUsed) as cm:
  2110. with self.override_router():
  2111. auth.book_set.update(title="Different")
  2112. e = cm.exception
  2113. self.assertEqual(e.mode, RouterUsed.WRITE)
  2114. self.assertEqual(e.model, Book)
  2115. self.assertEqual(e.hints, {"instance": auth})
  2116. class NoRelationRouter:
  2117. """Disallow all relations."""
  2118. def allow_relation(self, obj1, obj2, **hints):
  2119. return False
  2120. @override_settings(DATABASE_ROUTERS=[NoRelationRouter()])
  2121. class RelationAssignmentTests(SimpleTestCase):
  2122. """allow_relation() is called with unsaved model instances."""
  2123. databases = {"default", "other"}
  2124. router_prevents_msg = "the current database router prevents this relation"
  2125. def test_foreign_key_relation(self):
  2126. person = Person(name="Someone")
  2127. pet = Pet()
  2128. with self.assertRaisesMessage(ValueError, self.router_prevents_msg):
  2129. pet.owner = person
  2130. def test_reverse_one_to_one_relation(self):
  2131. user = User(username="Someone", password="fake_hash")
  2132. profile = UserProfile()
  2133. with self.assertRaisesMessage(ValueError, self.router_prevents_msg):
  2134. user.userprofile = profile