Django discusses the problem of generating SQL statements according to configuration

  • 2020-09-28 09:00:16
  • OfStack

To generate SQL statements based on the model and configuration in django, you need to make 1 set first:

First, you need to enter the setting.py file in your app folder. There is 1 DATABASES in it to set up the configuration information of the database:


DATABASES = { 
 'default': { 
  # 'ENGINE': 'django.db.backends.sqlite3', 
  # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 
  'ENGINE': 'django.db.backends.mysql', 
  'NAME': ' The name of your database ', 
  'USER': ' The user name ', 
  'PASSWORD': ' password ', 
  'HOST': '', 
  'PORT': '3306', 
 } 

Next you need to activate your app, again in the setting.py file, there is an INSTALLED_APPS, add your app to the end,


INSTALLED_APPS = [ 
 'django.contrib.admin', 
 'django.contrib.auth', 
 'django.contrib.contenttypes', 
 'django.contrib.sessions', 
 'django.contrib.messages', 
 'django.contrib.staticfiles', 
 ' your app The name of the ', 
] 

The model is defined and activated, and the next command to verify that the model is valid is python manage.py validate in the previous version

If your version of Django is relatively new (mine is 1.10), an error message may appear:


Unknown command: ‘validate‘

Type ‘manage.py help‘ for usage.

So the new version of the validation command is python ES32en. py check

After we verify that we can generate the SQL statement, you may need to write something in model.py 1 before you want to generate the SQL statement,

The previous version of the command was python manage. py sqlall *** (your app name)

If the version does not match, an error message will appear:


Unknown command:  ' sqlall ' 

Type  ' manage.py help '  for usage.

Similarly, if you want to submit sql statements to the database and run syncdb, the error message is:


Unknown command:  ' syncdb ' 
Type  ' manage.py help '  for usage. 

The current newer version of django commands are:


python manage.py makemigrations books # Used to detect database changes and generate database migration files 

python manage.py migrate # Used to migrate databases 

python manage.py sqlmigrate books 0001 #  Used to convert database migration files into database language 

After executing these three commands in sequence on the command line, you can access the data.


Related articles: