copy contents of one table to another table in django - python

How do I copy all the rows in a django table to a new table while retaining the old table contents?

Execute raw SQL directly:
from django.db import connection, transaction
cursor = connection.cursor()
# commit required
cursor.execute("SELECT * INTO %s FROM %s" % (newtable, oldtable))
transaction.commit_unless_managed()
Working from model objects, the table name will be stored in _meta.db_table

Related

How to automap tables in Oracle database in other schema

I login to Oracle database with user1, but all tables are in schema 'public'.
SQL> SELECT * FROM user_tables;
no rows selected
SQL> SELECT COUNT(*) FROM all_tables;
COUNT(*)
----------
5409
Refer to sqlalchemy Oracle docs I autoload one table by using oracle_resolve_synonyms or specific schema=public and it works:
Table('AINDEXEODPRICES',
Base.metadata,
autoload_with=engine,
oracle_resolve_synonyms=True)
The doc says
oracle_resolve_synonyms is accepted wherever reflection arguments are accepted, including methods such as MetaData.reflect() and Inspector.get_columns().
But if I try:
# produce our own MetaData object
metadata = MetaData()
​
# we can reflect it ourselves from a database, using options
# such as 'only' to limit what tables we look at...
metadata.reflect(engine, oracle_resolve_synonyms=True)
​
Base = automap_base(metadata=metadata)
​
# calling prepare() just sets up mapped classes and relationships.
Base.prepare()
​
print(metadata.tables)
It still got empty result FacadeDict({}).
So, how to correctly reflect tables in Oracle database?

create a copy of all tables with its key and other constraints from sql-server database to another database

I try to copy the sql-server's table with its keys and other constraints through SQLAlchemy in python
`from sqlalchemy import *
DATABASE_CONN = f'mssql://#{SERVER}/{DATABASE}?driver={DRIVER}'
DATABASE_CONN2 = f'mssql://#{SERVER}/{DB2}?driver={DRIVER}'
engine = create_engine(DATABASE_CONN)
engine2 = create_engine(DATABASE_CONN2)
connection = engine.connect() connection2 = engine2.connect()
metadata = MetaData() table = Table('table_name', metadata, autoload=True, autoload_with=engine) table.create(engine2)
ERROR:
sqlalchemy.exc.NoSuchTableError: table_name
if i putting the specific table name instead of 'table_name' then it create that table in new databse but i have to do it for all table so any technique to resolve this issue and make the copy of all table with its keys and other constraint at one go.
You recreate all the table schema from one database in a second by reflecting the first into a metadata object and then creating the tables in the second:
meta = MetaData()
meta.reflect(engine)
meta.create_all(engine2)
It's possible to control precisely which tables get reflected - review the docs for Reflecting Database Objects and metadata.reflect.

Multiple Django Database Connection [duplicate]

I have a Django project that utilizes multiple databases. https://docs.djangoproject.com/en/dev/topics/db/multi-db/
I perform a lot of raw queries like this:
cursor = connection.cursor()
cursor.execute("select * from my_table")
....
transaction.commit_unless_managed()
How can I specify which database to use?
Refer django docs on executing custom query directly. Specify database in your connection as given below:
from django.db import connections
cursor = connections['db_alias'].cursor()
cursor.execute("select * from my_table")
And then commit using
from django.db import transaction
transaction.commit_unless_managed(using='db_alias')
try this may be it should works.
from django.db import connections
cursor = connections[’my_db_name’].cursor()
# Your code here...
transaction.commit_unless_managed(using=’my_db_name’)

Django migrations. How to check if table exists in migrations?

I'm currently working on app built on Django 1.8 and Postgres. This app is installed in several environments, in some of them there old tables in DB from which i need to delete records.
I wrote migration with following SQL query:
IF EXISTS (
SELECT relname FROM pg_class WHERE relname=tablename
) THEN
DELETE FROM tablename END IF;
But Django throws error at this query:
django.db.utils.ProgrammingError: syntax error at or near "IF"
Can i somehow check, in migration, that table exists, and only then execute query, like DROP FROM tablename ?
The easiest way to check if a table exists is to use django.db.connection.introspection.table_names():
from django.db import connection
...
all_tables = connection.introspection.table_names()
old_tables = set('old_table_1', 'old_table_2')
existing_old_tables = old_tables.union(all_tables)
# clean tables in existing_old_tables with migrations.RunSQL() as suggested above
Solved it using django.db.connection. Code:
from django.db import migrations
from django.db import connection
class Migration(migrations.Migration):
db_cursor = connection.cursor()
check_exists_query = "SELECT relname FROM pg_class WHERE relname=%s;"
base_query = "DELETE FROM {table} WHERE condition;"
tables = [tables]
existing_tables = []
for table in tables:
db_cursor.execute(check_exists_query, [table])
result = db_cursor.fetchone()
if result:
existing_tables.append(table)
operations = [
migrations.RunSQL(base_query.format(table=existing_table)) for existing_table in existing_tables
]

Querying a for table not defined in models Sqlalchemy

I have this table in my database (using Posgresql and Sqlalchemy) called "participants".
In my models.py I want to access the participant's records. Since participants is not in my models.py and resides as a table in my db, when I do query = db.session.query('participants').order_by('name').all() I get an error:
ProgrammingError: (ProgrammingError) column "participants" does not exist
LINE 1: SELECT participants ORDER BY name
^
What can I do to retrieve this information?
Like the comment on the original post, did something like:
query = db.engine.execute('select * from participants order by name')
This doesn't give it in the same format as the query so I could use it for what I needed (a dictionary output, and a format for web), so I did:
partner_list = []
for record in query:
record_dict = dict(record)
partner_list.append(record_dict)

Categories