Glueon
Glueon

Reputation: 4017

Django models with external DBs

I have a typical Django project with one primary database where I keep all the data I need.

Suppose there is another DB somewhere with some additional information. That DB isn't directly related to my Django project so let's assume I do not even have a control under it.

The problem is that I do ont know if I need to create and maintain a model for this external DB so I could use Django's ORM. Or maybe the best solution is to use raw SQL to fetch data from external DB and then use this ifo to filter data from primary DB using ORM, or directly in views.

The solution with creating a model seems to be quite ok but the fact that DB isn't a part of my project means I am not aware of possible schema changes and looks like it's a bad practice then.

So in the end if I have some external resources like DBs that are not related to but needed for my project should I:

Upvotes: 1

Views: 519

Answers (3)

knbk
knbk

Reputation: 53679

An alternative is to use SQLAlchemy for the external database. It can use reflection to generate the SQLAlchemy-equivalent of django models during runtime.

It still won't be without issues. If your code depends on a certain column, it would still break if that column is removed or changed in an incompatible way. However, it will add a bit more flexibility to your database interactions, e.g. a Django model would definitely break if an int column is changed to a varchar column, but using database reflection, it will only break if your code depends on the fact that it is an int. If you simply display the data or something, it will remain fully functional. However, there is always a chance that a change doesn't break the system, but causes unexpected behaviour.

If, like Benjamin said, the external system has an API, that would be the preferred choice.

Upvotes: 2

Benjamin Cbr
Benjamin Cbr

Reputation: 536

I would create the minimal django models on the external databases => those that interact with your code:

Several outcomes to this

  1. If parts of the database you're not interested in change, it won't have an impact on your app.
  2. If the external models your using change, you probably want to be aware of that as quickly as possible (your app is likely to break in that case too).
  3. All the relational databases queries in your code are handled by the same ORM.

Upvotes: 0

Wille
Wille

Reputation: 21

I suggest you to read about inspectdb and database routers. It's possible to use the django ORM to manipulate a external DB. https://docs.djangoproject.com/en/1.7/ref/django-admin/#inspectdb

Upvotes: 0

Related Questions