Django read and write from multiple databases - python

Hello guys I'm developing a web app in django and I'm using the postgresql database. I must be able also to grab some data from another app which uses a sqlserver database. The tables that I'm trying to get have lots of data so maybe it is not wise to use a direct link. Which is the best approach regarding this issue? Can I use a sql-odbc connection to get the data, also how can I populate the tables lets say I create a local table and migrate data from sql to postgresql schedualy. Would like to understand how you dealt with this issue and your experiences. Thank you!

In your settings.py edit this code (for multiple databases)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'django',
'USER': 'postgres',
'PASSWORD': '12345678',
'HOST': 'localhost',
'PORT': '5432',
},
'connection_other_db': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mi_db',
'USER': 'root',
'PASSWORD': 'root',
'HOST': 'localhost',
'PORT': '3306',
}
}
Apply migrations command:
For default database
$ ./manage.py migrate
For other database (connection_other_db)
$ ./manage.py migrate --database=connection_other_db
In you views,
For using ORM, use this:
Mi_Model.objects.using('connection_other_db').all() # For mysql database
Mi_Model.objects.all() # For default database (postgresql)
For create object:
s = Mi_Model()
s._state.adding = False
s._state.db = 'connection_other_db'
s.field_1 = 'A value'
s.save()
or
s = Mi_Model.objects.using('connection_other_db').create(
field_1='A value'
# ....
)
For use transactions:
with transaction.atomic(using='connection_other_db'):
# Your code here
For use cursors
with connections['connection_other_db'].cursor() as cursor:
cursor.execute('your query')
Django documentation:
https://docs.djangoproject.com/es/2.1/topics/db/multi-db/

Related

Can I access other MySQL database in Python Django without having access to its models?

I have this connection to MySQL Workbench database. The thing is, the database and tables isn't made by my Django project so I don't have any access to its class models. Is there any way I can add, update or delete in the database tables?
tables: TestTable1, TestTable2, TestTable3
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test',
'USER': 'root',
'PASSWORD': '1234',
'PORT': 3306,
'HOST': '127.0.0.1',
'OPTIONS': {
'charset': 'utf8mb4',
'use_unicode': True, },
}
}
You can use custom sql directly. Have a look at:
https://docs.djangoproject.com/en/3.2/topics/db/sql/#executing-custom-sql-directly

Django not finding database despite it existing

I'm trying to change the default database used in Django to MySQL, I've adjusted my settings.py file like so:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'clients',
'HOST': 'localhost',
'PORT': '3307',
'USER': 'root',
'PASSWORD': '*****',
}
}
I'm still getting the django.db.utils.OperationalError: (1049, "Unknown database 'clients'"). When I try to connect to the 'mysql' database that comes default with MySQL I have no issue. I get this error when I try to use manage.py makemigrations,migrations or runserver. I have MySQL-Python installed and everything. Proof that my clients database exists:

django.db.utils.OperationalError: (1046, 'No database selected')

Getting a strange error. I created a database in MySQL, set the database to use it. Using the right settings in my Django settings.py. But still there's an error that no database has been selected.
First I tried:
python manage.py syncdb
Got this traceback:
django.db.utils.OperationalError: (1046, 'No database selected')
settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'my_db',
'USER': 'username',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '3306',
}
}
What have I missed?
Check to make sure your database my_db exists in your MySQL instance. Log into MySQL and run;
show databases;
make sure my_db exists. If it does not, run
create database my_db;
GRANT access privileges to the user mentioned in the file
GRANT ALL PRIVILEGES ON database_name.* TO 'username'#'localhost';
You need not grant all privileges. modify accordingly.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'my_db',
'USER': 'username',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '3306',
}
}
Here name means database
Just delete database my_db and create again
Step 1:- Use drop database databaseName
Step 2:- Create Database databaseName
Then use the migrate command
It will definitely work

Multiple Databases in Django

I've 2 DB in my one Django app. The two DB's are on the same network, ie on LAN. So, I suppose the HOST IP will be different. Wouldnt it be?
As of right now, to test my code, I've provided same HOST but different PORT.
So, my DB settings are as follow:-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'vms_db',
'USER': 'root',
'PASSWORD': '',
'HOST': '127.0.0.1',
'PORT': '8000',
},
'users': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'aramex_vms_db',
'USER': 'root',
'PASSWORD': '',
'HOST': '127.0.0.1',
'PORT': '8080',
}
}
When I syncdb it, it returns an error saying:-
django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (111)")
But when I use the same port, it works fine but the tables are made in default DB. I know the migrate command by default works on default DB.
1) But what if I want that there should be different tables for default and different for users, how will I do that?
If you want to migrate your database users:
$ ./manage.py migrate --database=users
As you can see here: https://docs.djangoproject.com/en/dev/topics/db/multi-db/#synchronizing-your-databases
If you want to select your database while you retrieve an entry:
#default dabatase
Author.objects.all()
#custom database
Author.objects.using('DATABASE_NAME').all()
Further information: https://docs.djangoproject.com/en/dev/topics/db/multi-db/#manually-selecting-a-database

1049, "Unknown database 'database' " django mysql can't connect

Exception Type: OperationalError at /
Exception Value: (1049, "Unknown database 'database'")
At the moment i tried this:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'database', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': '****', # Not used with sqlite3.
'HOST': '/var/lib/mysql/database/', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '80', # Set to empty string for default. Not used with sqlite3.
}
}
If i don't specify a host i get this error:
OperationalError at /
(2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/database' (13)")
Can it be something with permissions?
thanks in advance :)
First, create the database on mysql.
Second, edit your default conection like this.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'MY_DATABASE_NAME',
'USER': 'root',
'PASSWORD': 'MY_PASSWORD',
}
}
finally run your syncdb.
./manage.py syncdb
PORT is not the web server port, but the database port, which is 3306 for MySQL, and HOST is the database sever's IP or name. You probably want 127.0.0.1.
You should create the database beforehand with create database mydatabase charset utf8; from the mysql prompt.
Login to mysql on Terminal and create a DB
mysql -u root -p
CREATE DATABASE dbname;
USE dbname;
Then on setting.py file
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'dbname',
'USER': 'root', #Mysql username
'PASSWORD': 'password', #mysql password
'HOST': 'localhost', # Or an IP Address that your DB is hosted on
'PORT': '3306',
}
}
I dont think you can create a database by the name database. So please check the following first...
1) Have installed mysql-server and created the database with proper grant all permissions? If you have done so then check next steps
2)I dont know about Amazon, but this error was common in older versions of Linux distros from Redhat and Fedora. An option is to do this
by setting the SELINUX line in /etc/sysconfig/selinux to Disabled:
SELINUX=Disabled

Categories