Friday, September 22, 2017

Question about Multiple DBs and Foreign Keys


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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/cdf8328c-5370-4566-87ee-e79df475a4f1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment