SoFunction
Updated on 2024-11-07

How django connects to databases with existing data

Has this ever happened to you?

database, various table structures have been created, even the data, at this point, I want to use Django to manage this database, ORM mapping how to do?

Django is best suited for so-called green-field development, i.e. starting a new project from scratch!

But then, Django also supports integration with previous legacy databases and applications.

Django's database layer generates SQL schemas from Python code, but for legacy databases, you're already using SQL schemas, in which case you need to write models for your pre-existing database tables (in order to use the database's APIs), and fortunately, Django comes with the Auxiliary tool inspectdb

Is the sqllit database used by default? How to use MySQL database?

# Modify the file

DATABASE = {
  'default':{
    'ENGINE':'',
    'NAME':'database name',
    'HOST':'Database address',
    'PORT':port,'
    'USER':'user ID',
    'PASSWORD':'cryptographic',
  }
}
# Since Django internally links to MySQL databases by default using MySQLdb's
#But there's no such module in Python 3 #
#So we're going to modify the __init__ file in his project's folder of the same name.

import pymysql
pymysql.install_as_MySQLdb()

Then we need to auto-generate new mods based on the database.

python  inspectdb  #One can simply look at the automatic mapping intomodelshit the nail on the head

Export and replace

python  inspectdb > 

You will see that a file has been generated in the same level directory as the

Use this file to overwrite the mods file in the app.

If you've done the above, and you've generated mods that can't be modified/deleted, change managed = True in the meta class to tell django that it can operate on the database.

At this point, we go back to synchronizing with the database

python  migrate

It's a big deal at this point!

summarize

The above is the entire content of this article, I hope that the content of this article for your study or work has a certain reference learning value, thank you for your support.