15

I want to select data from a database table that is not part of my Django project. I added the database connection info to the settings file and I can do raw sql queries against it to pull the data. However, I would like to create a model for that table and be able to access the data as I would any other Django model data.

Is this possible? I can find any documentation on that.

2 Answers 2

22

The Django: Multiple Databases page contains good information on this topic. After you have configured your databases in settings.py, you can use .using() to specify the database you wish to query.

Examples from the documentation:

>>> # This will run on the 'default' database.
>>> Author.objects.all()

>>> # So will this.
>>> Author.objects.using('default').all()

>>> # This will run on the 'other' database.
>>> Author.objects.using('other').all()
Sign up to request clarification or add additional context in comments.

4 Comments

What is Author then? Author model is not defined in models.py.
Author in this case is a placeholder for any object you wish to query. I simply copied the example from the documentation at the linked page. You can use any object.
Can you tell me how to execute raw queries like this? Ex:Author.objects.using('other').raw("Select * from table1")
For query purposes i recommend the use of 'Database Routers'. However, this is a very nice approach to create a classmethod in any model to copy data between databases. ;)
4

sure, you just have to use

SomeObject.objects.using('database_name').all()

to do your queries

Comments

Your Answer

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