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