问题
I have a django application using multiple databases. Given an instance of a model, how can I obtain the database where it is stored (if any)? I need this to save another object to the same database as the first.
def add_ducks_to_hunt(hunter):
db = # the hunter's db
duck = Duck()
duck.save(using=db)
回答1:
Use _state.db
, as in:
my_obj = MyModel.objects.get(pk=1)
my_obj._state.db
This is shown in the routing example.
回答2:
I believe you are looking for settings.py in the project (top level) Django directory. If not, would you post more information?
Here is a bit of my settings.py file in the Django project directory /home/amr/django/amr.
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Somone R. Somebody'so-forath-and-so-and-so@somewhere.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'ENGINE': 'mysql',
'NAME': 'some-server-name', # Or path to database file if using sqlite3.
'USER': '<user>', # Not used with sqlite3.
'PASSWORD': 'xxxxxxxx', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
SESSION_COOKIE_AGE = 15 * 60 * 60 # Age of cookie, in seconds
回答3:
If you always save a model in the same db, you could store that info in model class and then use it when needed. Probably not very pythonic, but it may do the trick.
Class Hunter(models.Model):
# ... other stuff
db = 'hunter_db'
Access it then with __class__
:
def add_ducks_to_hunt(hunter):
db = hunter.__class__.db
duck = Duck()
duck.save(using=db)
On the other hand, if you save objects of one class in different databases, than I see no other way than to write each object's id and db name at object's save() to a table somewhere you can always access it and use that info to load the object.
回答4:
There is no way to directly get the info from a model instance itself. Ah, _state, yes. its You should explicitly pass in 'using' parameter, just like those built-in methods. Or design router which could deduce the DB to use by check some facts of the model instance, here the hunter.
来源:https://stackoverflow.com/questions/9929629/how-to-get-the-database-where-a-model-instance-was-saved-to-in-django