geek
geek

Reputation: 816

django model creation connecting to mssql

I am connecting to a legacy mysql database in cloud using my django project. i need to fetch data and insert data if required in DB table.

do i need to write model for the tables which are already present in the db? if so there are 90 plus tables. so what happens if i create model for single table? how do i talk to database other than creating models and migrating? is there any better way in django? or model is the better way? when i create model what happens in the backend? does it create those tables again in the same database?

Upvotes: 1

Views: 974

Answers (1)

FlipperPA
FlipperPA

Reputation: 14311

There are several ways to connect to a legacy database; the two I use are either by creating a model for the data you need from the legacy database, or using raw SQL.

For example, if I'm going to be connecting to the legacy database for the foreseeable future, and performing both reads and writes, I'll create a model containing only the fields from the foreign table I need as a secondary database. That method is well documented and a bit more time consuming.

However, if I'm only reading data from a legacy database which will be retired, I'll create a read-only user on the legacy database, and use raw SQL to grab what I need like so:

from django.db import connections

cursor = connections["my_secondary_db"].cursor()

cursor.execute("SELECT * FROM my_table")

for row in cursor.fetchall():
    insert_data_into_my_new_system_model(row)

I'm doing this right now with a legacy SQL Server database from our old website as we migrate our user and product data to Django/PostgreSQL. This has served me well over the years and saved a lot of time. I've used this to create sync routines all within a single app as Django management commands, and then when the legacy database is done being migrated to Django, I've completely deleted the single app containing all of the sync routines, for a clean break. Good luck!

Upvotes: 1

Related Questions