Dynamic database routing in Django

97 views
Skip to first unread message

Philip Goh

unread,
Mar 12, 2014, 5:44:50 PM3/12/14
to django...@googlegroups.com
Hello list,

In my database, I have a `Customer` table defined in my database that all other tables are foreign keyed on.

    class Customer(models.Model):
        ...

    class TableA(models.Model):
        Customer = models.ForeignKey(Customer)
        ...

    class TableB(models.Model):
        Customer = models.ForeignKey(Customer)
        ...


I'm trying to implement a database router that determines the database to connect to based on the primary key of the `Customer` table. For instance, `id`s in the range 1 - 100 will connect to Database A, `id`s in the range 101 - 200 will connect to Database B. 

I've read through the Django documentation on [routers](https://docs.djangoproject.com/en/dev/topics/db/multi-db/#using-routers) but I'm unsure if what I'm asking is possible. Specifically, the methods `db_for_read(model, **hints)` and `db_for_write(model, **hints)` work on the **type** of the object. This is not helping me as I need routing to be based on the contents of the instance of the object. The documentation further states that the only `**hints` provided at this moment are an `instance` object where applicable and in some cases no `instance` is provided at all. This doesn't inspire me with confidence as it does not explicitly state the cases when no `instance` is provided.

I'm essentially attempting to implement application level sharding of the database. Is this possible in Django?

Kind regards,
Phil

Xavier Ordoquy

unread,
Mar 13, 2014, 2:51:35 AM3/13/14
to django...@googlegroups.com
Hi Philip,

I’m not sure your sharding will be possible in the way you describe it.

There will be cases for which selecting the database will not be possible. For example, Customer.objects.get(name=xxxx) won’t be able which DB you’ll need to hit to get the result.
Same goes for a new Customer. How would you know its ID before the DB saves it ?

Regards,
Xavier,
Linovia.

--
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...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a6422b0f-deba-4f56-953d-4db250cfd948%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages