2

Is there a way to connect sqlalchemy to the django db? I am running a django test where a test database is created connection._connections.settings['default'] gives:

{'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test_db', 'USER': 'postgres', 'PASSWORD': 'qwertyu', 'HOST': 'localhost', 'PORT': '5432', 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'OPTIONS': {}, 'TIME_ZONE': None, 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIGRATE': True, 'MIRROR': None, 'NAME': None}}

But if I try to connect to this database using sqlalchemy:

user = settings.DATABASES['default']['USER']
        password = settings.DATABASES['default']['PASSWORD']
        database_name = settings.DATABASES['default']['NAME']

        database_url = 'postgresql+psycopg2://{user}:{password}@localhost:5432/{database_name}'.format(
            user=user,
            password=password,
            database_name=database_name,
        )

        engine = create_engine(database_url, echo=False)

a completely new database is created. So any data inserted using model.bulkcreate() live is a different database than the one created by sqlalchemy.

I would like to be able to use both. I want to use sqlalchemy for long time series (1M to 10M rows) where model.bulkcreate() is taking very long.

I find it weird that the engine of connection is 'django.db.backends.postgresql', while the engine of sqlalchemy is postgresql+psycopg2 or postgresql.

Is there a way to connect connection with sqlalchemy?

thanks

2
  • SQLAlchemy does not create a new database when connecting to a Postgresql server. You could create a SQLAlchemy script that populates your dattabase outside of Django, but AFAIK Django does not support SQLAlchemy as a database backend or model provider (but I am not up to date wiht Django, so there could be third party tools for this). Understand that Django engines and SQLAlchemy engines are different things and are not interchangeable. Commented Jul 19, 2022 at 8:00
  • found it. rodic.fr/blog/sqlalchemy-django Commented Jul 19, 2022 at 22:46

1 Answer 1

2

I found aldjemy in a blog here. https://rodic.fr/blog/sqlalchemy-django/

all that is needed is this

from aldjemy.core import get_engine
engine = get_engine()
df.to_sql(table_name, con=engine)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.