How to use other than default database - python

I am creating a project that supports multiple databases. I have written queries in models, and I need to save those details in a selected database.
I have two databases: SQLite3 and MongoDB. Now I need to save those query details in SQLite3. How do I do it? I am using Python 2.7 and Django 1.5.4.
Here is the code in settings.py:
DATABASES = {
'default': {},
'sqlite':
{
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(APP_DIR, 'mydb.sqlite3'),
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
},
'mongodb':
{
'ENGINE': 'django_mongodb_engine',
'NAME': "mydb",
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
And here is the code in models.py:
from django.db import models
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
def __unicode__(self):
return self.name

Use using argument if you use save method.
blog = Blog(name='This is a blog post', tagline='python django')
blog.save(using='sqlite')
or use db_manager if you use create method:
blog = Blog.objects.db_manager('sqlite').create(
name='This is a blog post', tagline='python django')
For other operations, see Multiple databases - Django documentation.

Related

Wrong model._meta.app_label (from other app) in Django database router

i have two different SQL databases and three apps in my django project.
The apps are named PROD, TEST and common.
I am trying to route everything that comes from an url of PROD to models.py from PROD and database1, and everything that comes from an url of TEST to models.py from TEST and database2.
TEST
-- models.py
PROD
-- models.py
common
It worked fine, until i introduced 'common'(after cloning the project to another folder) and i don't know why.
settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'cfg_db_ic2_net_dev_test',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
},
'proddb': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'cfg_db_ic2_net_dev_prod',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
DATABASE_ROUTERS = ['PROD.dbRouter.ProdDBRouter']
PROD/dbRouter.py:
def db_for_read(self, model, **hints):
"Point all operations on prod models to 'proddb'"
from django.conf import settings
print(model._meta.app_label)
if model._meta.app_label == 'PROD':
return 'proddb'
return None
...
PROD/views.py:
def hosts(request):
print("I did this")
return render(request=request, template_name="common/hosts.html", context={"hosts": NetDefined.objects.all, "landscape": landscape})
The models.py for each TEST and PROD is pretty identical.
The issue that i have is that the template hosts.html is populated with data from the default data base and not from proddb database.
The reason for this is that the DBRouter doesn't recognize the model's model._meta.app_label, it says it's "TEST".
Even though the url is definitely routed correctly, the "I did this" is printed.
This only occured after reinstalling the project and introducing the third app.
So my question is: why doesn't Django recognize, that the views and models from "PROD" are being used and instead provides the wrong app_label to the router?
Thanks for your help!

insert in database that is not the default DJANGO

I know django works with multiple database connections, I need to insert in a database that is not the default, but I get the following error.
ProgrammingError at /api-jde/f59presapi/2279/
(1146, 'Table \'dblocal."oracle"."FPRES"\' doesn\'t exist')
this is the configuration of my settings.py file
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'dblocal',
'USER': 'root',
'PASSWORD': '',
'HOST': '',
'PORT': '',
},
'bd2': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'XXXX',
'USER': 'oracle',
'PASSWORD': 'xxxxx',
},
}
the bd in which I need to insert is the db2 (I'm not putting all the data here but if I have them full), in the created model I have the METa configuration with the following:
class Meta:
managed = False
db_table = u'"oracle"."FPRES"'
db = DATABASES['db2']
Perhaps this will help if added to the meta class.
As far as I know you can't specify a database for a specific model. You need to do something like this every time:
YourModel.objects.using('bd2').all()
Hope this helps.

Multiple Databases --Migrations

I am using 2 postgres databases in my django app.
'newpostgre': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'new_postgre2',
'USER': 'tester',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '',
},
'newpostgre2': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'new_postgre3',
'USER': 'tester',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '',
},
I have a very simple model
class Check1(models.Model):
title = models.CharField(max_length=100)
I had run
python manage.py migrate --database=newpostgre
python manage.py migrate --database=newpostgre2
when I open my new_postgre2(for newpostgre) database in postgre, I can see my Check1 table there.
But in my new_postgre3(for newpostgre2) database in postgre, no Check1 table is there, only those initial migrations are there.
Why I can't see my table in new_postgre3 when migrations have been successfully made?
Because The same object name can be used in different schemas sometimes conflict. The best practice allow many users to use one database without interfering with each other. Use this change second database user and check again. I think it is work.
'newpostgre': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'new_postgre2',
'USER': 'tester',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '',
},
'newpostgre2': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'new_postgre3',
'USER': 'tester_different',
'PASSWORD': 'password_different',
'HOST': 'localhost',
'PORT': '',
},
python manage.py migrate --database=newpostgre2

Want to implement multiple database in django project

I want to use multiple sqlite3 database for my app. I want to write some of the data(which is user log) to one database and rest of the stuff to another db. After that I want to read from both the database.
Thanks
DATABASE_ROUTERS = ['manager.router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = { 'db_b':'db_b'}
DATABASES = {
'default': {
'ENGINE': 'backend_of_your_choice',
'NAME': 'default',
'USER': 'xxx',
'PASSWORD': 'xxx',
'HOST': '127.0.0.1',
'PORT': '',
},
'db_b': {
'ENGINE': 'backend_of_your_choice',
'NAME': 'db_b',
'USER': 'xxx',
'PASSWORD': 'xxx',
'HOST': '127.0.0.1',
'PORT': '',
},}
Then in your model MetaClass define the following for all the models which you want to use db_b:
class Meta:
app_label = 'db_b'

How to use a specific database for a single test in django?

Does anyone kno how to use a specific database for a single test in Django?
EDIT: At the moment, i'm using sqlite for testing, but, i want to use a mysql database for a specific test (def test_benchmark...), which will benchmark some sql statements.
Thanks
I don't know of any builtin way to do it - but I didn't look for it neither honestly. One possible (dirty) hack is to check what's in sys.argv in your settings (which is just another Python module) and have an alternate database settings for your particular test, ie:
# settings.py
import os, sys
DATABASES = {
'default': {
'NAME': 'db_name',
'ENGINE': 'your.engine',
'HOST': 'server',
'USER': 'django',
'PASSWORD': 'django',
}
}
if "test" in sys.argv and "your-test-name" in sys.argv:
DATABASES = {
'default': {
'NAME': 'other_db_name',
'ENGINE': 'your.engine',
'HOST': 'server',
'USER': 'django',
'PASSWORD': 'django',
}
}
In Django you set the database in your settings.py file. The configuration should look something like this:
DATABASES = {
'default': {
'NAME': 'db_name',
'ENGINE': 'sql_server.pyodbc',
'HOST': 'server',
'USER': 'django',
'PASSWORD': 'django',
'OPTIONS' : { "use_mars" : False,
"provider" : "SQLNCLI10",
"extra_params" : "MARS Connection=True"},
}
}

Categories

Resources