#14121: Provide object's primary key as a hint for database router method
db_for_read() when filtering objects by primary key
------------------------------------------+---------------------------------
Reporter: [email protected] | Owner: nobody
Status: new | Milestone:
Component: Database layer (models, ORM) | Version: 1.2
Keywords: router, hints | Stage: Unreviewed
Has_patch: 0 |
------------------------------------------+---------------------------------
'''Problem:'''
Setting up a custom database router with db_for_read() method to allow for
sharding with MySQL. Need to be able to control what database an object is
read from on a per-object basis.
[[BR]]
[[BR]]
'''Example Case:'''
I want to retrieve User objects from the database cluster as follows:
* If the username starts with a number, read from slave_db_1
* If the username starts with a letter, read from slave_db_2
[[BR]]
Currently, the only way to achieve this behavior is to specify "using" on
each condition, and per each call to the database.
[[BR]]
[[BR]]
'''Proposed Solution:'''
[[BR]]
[[BR]]
When filtering objects by primary key, pass the primary key to
db_for_read() as a hint.
[[BR]]
[[BR]]
'''Example Code:'''
{{{
#View Code:
"""Assume username is pk for User model"""
users = User.objects.get(username="testuser")
#DB Router Code
class UserReadRouter(object):
def db_for_write(self, model, **hints):
return 'master'
def db_for_read(self, model, **hints):
"""Assume pk of User object is a string"""
if model.__name__ == "User" and 'object_pk' in hints:
if hints['object_pk'][0].isalpha():
return 'slave_db_2'
else:
return 'slave_db_1'
}}}
[[BR]]
[[BR]]
The end result is that "testuser" is retrieved from slave_db_1.
--
Ticket URL: <http://code.djangoproject.com/ticket/14121>
Django <http://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-updates?hl=en.