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.
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()
sure, you just have to use
SomeObject.objects.using('database_name').all()
to do your queries
Related
I have several Django applications and they need to share one database on Heroku. I may specify the shared database on each statement that need to access it, for example:
from account.models import User
if DEBUG: # Running locally
users = User.objects.all() # 'default' DB
else: # Running on Heroku
users = User.objects.using('shared').all() # 'shared' DB
I have two questions:
1) Specifying the shared database on every statement is really tedious. Is it possible to set the shared database once for all (maybe in setting.py)? For example:
from account.models import User
if not DEBUG: # Running on Heroku
User = User.objects.using('share') # This is hypothetical!!
users = User.objects.all()
2) How do I set the shared DB for a foreign key. For example:
from account.models import User
class Article(models.Model):
author = models.ForeignKey(User) # How to set 'User' to come from 'shared' DB?
Django database routers have what you are looking for
https://docs.djangoproject.com/en/2.0/topics/db/multi-db/#using-routers\
Relations do not work cross database
https://docs.djangoproject.com/en/dev//topics/db/multi-db/#limitations-of-multiple-databases
I recommend trying to keep everything in 1 database initially. Usually when starting out there isn't going to be a need to separate it out.
Just a simple question.
After I connect my django app to a remote database, I don't need to use Model.py to create tables in the database, then what is the function for Model.py at that moment?
If you want to use the Django ORM, you'll need to create models in the models.py file that match your remote database. If you don't want django creating or deleting tables on this DB, the managed=False option needs to be set for each model.
https://docs.djangoproject.com/en/1.11/ref/models/options/#managed
As you said after running migrations all tables in models.py file will be created. Later on, if you want to do some database operations, you may be using Django ORM. If you don't have models.py you won't be able to do such operations.
For example:
To create an entry to the table MyModel.
from your_app.models import MyModel
MyModel.objects.create(<field_name>=<value>)
I hope this gives you some idea.
In Django database username is used as schema name.
In DB2 there is no database level users. OS users will be used for login into the database.
In my database I have two different names for database user and database schema.
So in django with db2 as backend how can I use different schema name to access the tables?
EDIT:
Clarifying that I'm trying to access via the ORM and not raw SQLs. The ORM implicitly is using the username as the schema name. How do I avoid that ?
DB2 uses so-called two part names, schemaname.objectname. Each object, including tables, can be referenced by the entire name. Within a session there is the current schema which by default is set to the username. It can be changed by the SET SCHEMA myschema statement.
For your question there are two options:
1) Reference the tables with their full name: schemaname.tablename
2) Use set schema to set the common schemaname and reference just the table.
Got the solution for this:
1) We can use following query to change the schema in db2:
set schema schema_name;
2) We can execute above query at django startup.
We have to add following code in any of urls.py, manage.py files which will run it on startup.
def set_schema(sender, **kwargs):
from django.db import connection
cursor = connection.cursor()
try:
cursor.execute("set schema schema_name")
except Exception as e:
print str(e)
from django.db.backends.signals import connection_created
connection_created.connect(set_schema)
I am using django and postgresql db to develop my project, the db has 3 schemas. And I am writing raw quires using connection string to fetch data and insert data into tables.
Example:
from django.db import connection
query = "select * from schema1.records"
cursor = connection.cursor()
cursor.execute(query)
output = cursor.fetchall()
Like way I am using in my all views.
I wanted to write test cases to my views, so i need to generate fixtures to test my views, how to I generate fixtures for schemas and tables. Please help.
Note: I did not write any models i just used raw queries in my whole project.
Run:
manage.py dumpdata help
This will show how to use loaddata to generate fixtures.
In django models we have option named managed which can be set True or False
According to documentation the only difference this option makes is whether table will be managed by django or not. Is management by django or by us makes any difference?
Is there any pros and cons of using one option rather than other?
I mean why would we opt for managed=False? Will it give some extra control or power which affects my code?
The main reason for using managed=False is if your model is backed by something like a database view, instead of a table - so you don't want Django to issue CREATE TABLE commands when you run syncdb.
Right from Django docs:
managed=False is useful if the model represents an existing table or a database view that has been created by some other means. This is the only difference when managed=False. All other aspects of model handling are exactly the same as normal
When ever we create the django model, the managed=True implicitly is
true by default. As we know that when we run python manage.py makemigrations the migration file(which we can say a db view) is
created in migration folder of the app and to apply that migration i.e
creates the table in db or we can say schema.
So by managed=False, we restrict Django to create table(scheme, update
the schema of the table) of that model or its fields specified in
migration file.
Why we use its?
case1: Sometime we use two db for the project for
example we have db1(default) and db2, so we don't want particular
model to be create the schema or table in db1 so we can this or we can
customize the db view.
case2. In django ORM, the db table is tied to django ORM model, It
help tie a database view to bind with a django ORM model.
Can also go through the link:
We can add our raw sql for db view in migration file.
The raw sql in migration look like: In 0001_initial.py
from future import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.RunSQL(
CREATE OR REPLACE VIEW app_test AS
SELECT row_number() OVER () as id,
ci.user_id,
ci.company_id,
),
]
Above code is just for overview of the looking of the migration file, can go through above link for brief.