In the previous article we said that Mybatis-generator generated the code in reverse.
Here we begin to say how to reverse generate MySQL model code in Django.
Before we show the Django ORM reverse build, let's start by saying how to generate the code forward.
Forward generation, which refers to creating a model.py file, and then creating a model.py-compliant table in the database, such as MySQL, through the Django built-in compiler.
Reverse generation, which refers to creating a table in the database first, and then generating the model code through the Django built-in compiler.
1. Preparatory work
Create Django projects and apps
Create a Django project with the name HelloWorld
django-admin.py Startproject HelloWorld
Create an app with the name test
Python manage.py Startapp Hello
Configuration database
Configuring the database in setting.py
DATABASES = { 'default': { 'ENGINE':'Django.db.backends.mysql', 'NAME':'Big_data', 'USER':'Root', 'PASSWORD':'1234', 'HOST':'10.93.84.53', 'PORT':'3306', }}
2. Forward generation
Create a model.py in the Hello app directory
from Import Models class Alarmgroup (models. Model): = models. Charfield (Primary_key=true, max_length=250) = models. TextField (blank=true, null=True) = models. TextField (blank=true, null=True) = models. Datetimefield ()
To perform a command forward build
Python manage.py makemigrations
Python manage.py Migrate
You can view the table that was created successfully in the configured database
3. Reverse Generation
CREATE table in database now
CREATE TABLE ' Alarm_group ' ( varchar(notNULL, ' group_des ' blob, ' Members ' blob, 'timestampdatetimeis notNULL, ' on_duty ' blob, ' leader ' blob, PRIMARYKEY (' group_name ') ENGINE =DEFAULT CHARSET=UTF8
Then execute the command to generate the model.py code
Python manage.py Inspectdb
The generated code model.py is as follows
class Alarmgroup (models. Model): = models. Charfield (Primary_key=true, max_length=250) = models. TextField (blank=true, null=True) = models. TextField (blank=true, null=True) = models. Datetimefield () class Meta: = False 'alarm_ Group'
The db_table in this map the table names in the database.
Reverse generation of database Tables (ii) Django ORM Inspectdb