2

How can I configure models in Django which are being hosted in two different databases?

So far, I have 3 databases set up within my great Django environment. One of my apps uses a Router to automatically send data to the correct database -- this is easily done since this app only deals with that one database.

However, I have another app that uses two different databases. The app "controls" one of them, but gets data from a second that is updated through another application entirely.

I have tried adding an arbitrary attribute to the model's Meta class, to match against in the router, but this is not allowed in Django (as I discovered).

What data can I provide the model that can be matched against in the router, to know which database to go to?

4
  • I haven't tested this exact situation, but if you know when defining your model class which DB you want to use, you can set an arbitrary attribute to the class itself rather than its Meta class. Commented May 15, 2013 at 19:53
  • I've tried setting a db_name attribute within the regular model, but not all models have the attribute (and system models can't be forced to have it). My router chokes when it reaches these, despite my attempts to verify the attributes existence. In this case, how to a verify the attribute that might not be defined? Commented May 15, 2013 at 19:59
  • You could use hasattr to check, or just try/except and catch the exception. Commented May 15, 2013 at 20:02
  • Answer form so I may lavish with acceptance? Commented May 15, 2013 at 20:07

1 Answer 1

1

If you know when defining your model class which DB you want to use, you can add an arbitrary attribute to the class itself rather than its Meta class. In the router, you can then use hasattr to see if the attribute exists (since it won't for built in models), or just try/except and catch the exception.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.