Hi folks --
I'm trying to use multi-DB support for a one-off
operation to copy some data from one database to another with the same
schema, and trying to figure out how explicit one has to be about which
database to use for foreign key access. I understand that Django
doesn't support cross-DB foreign keys, but am trying to determine
whether it keeps track of which DB a model instance was retrieved from
in order to use the same DB for relationships if the DB for those models
isn't explicitly specified.
Imagine my models look like this:
class Author(models.Model):
name = models.CharField(max_length=255)
class Book(models.Model):
author = models.ForeignKey(Author, related_name='books')
title = models.CharField(max_length=255)
Will the following attempt to retrieve the books from the source DB or the default DB?
for author in Author.objects.using('source_db').all():
copy_stuff(author)
books = author.books.all()
for book in books:
copy_stuff(book)
And will the following attempt to retrieve the author from the source or the default DB?
for book in Book.objects.using('source_db').all():
do_stuff(book.author)
I
would just use select_related/prefetch_related (which I assume -
perhaps incorrectly? - will use the same DB as the primary query), but
the tables I'm working with are simply too large for loading all that
data into memory to be workable.
Do I need to instead explicitly make the queries for the related objects like so?
for book in Book.objects.using('source_db').all():
author = Author.objects.using('source_db').get(id=book.author_id)
do_stuff(author)
Thanks for your help!
-Noemi