Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django queryset "using()" method for specifying database doesn't work on related_name queries

Tags:

python

django

I've noticed something strange in Django that I haven't been able figure out. Let's say I have a Django application (I'm using 1.7) with two models like so:

class Bookstore(models.Model):
    name = models.CharField(max_length=50)

class Book(models.Model):
    title = models.CharField(max_length=100)
    store = models.ForeignKey(Bookstore, on_delete=models.PROTECT, related_name='books')

And then let's say I have two databases storing the data, perhaps a master-replica setup -- let's say the master is denoted as default in my settings file and the replica is replica. If I do the following query, I get an exception saying

the current database router prevents this relation

store = Bookstore.objects.using('default').get(id=1)
first_book = store.books.using('replica').all().order_by('id')[0]

However, the following, which should be the same query, works just fine:

store = Bookstore.objects.using('default').get(id=1)
first_book = Book.objects.using('replica').filter(store=store).order_by('id')[0]

What's going on here? Is there anyway to use the related_name lookup like the first example but have it work properly? Thanks!

like image 941
samskeller Avatar asked Mar 25 '26 19:03

samskeller


1 Answers

Look at SQL from first example (without using()):

SELECT "book"."id", "book"."title", "book"."store_id"
FROM "book" JOIN "bookstore" ON "book"."store_id" = "bookstore"."id"
WHERE "bookstore"."id" = 1
ORDER BY "book"."id"
LIMIT 1

Do You see the problem? You cannot do a SELECT on two databases.

And look at SQL from second example:

SELECT "book"."id", "book"."title", "book"."store_id"
FROM "book"
WHERE "book"."store_id" = 1
ORDER BY "book"."id"
LIMIT 1

Select data from one table.

like image 149
Tomasz Jakub Rup Avatar answered Mar 27 '26 07:03

Tomasz Jakub Rup