Reverse generating database table (b) Django ORM inspectdb
Here we begin to say how reverse mysql model to generate code in django.
Before we show django ORM in reverse to generate, let's talk about how to forward the generated code.
Forward generation, refers to create model.py file, and then django built-in compiler, such as creating a database table in the mysql in line with model.py.
Reverse generated, referring to Table create the database, then the built-django compiler generates a model code.
1, ready to work
Create a django project and app
Create a django project name is helloworld
django-admin.py startproject helloworld
Creating app, the name test
python manage.py startapp hello
Configuration database
Configuring the app in INSTALLED_APPS settings.py
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello', ]
Configuration database in settings.py
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'big_data', 'USER': 'root', 'PASSWORD': '1234', 'HOST': '10.93.84.53', 'PORT': '3306', } }
2, the forward generation
Model.py created in the directory hello app
from django.db import modelsclass AlarmGroup(models.Model):
group_name = models.CharField(primary_key=True, max_length=250)
group_des = models.TextField(blank=True, null=True)
members = models.TextField(blank=True, null=True)
timestamp = models.DateTimeField()
Run forward generation
python manage.py makemigrations
python manage.py migrate
Can go to the configuration database, view the successful creation of the table
3, the reverse generated
Now create tables in the database
CREATE TABLE `alarm_group` ( `group_name` varchar(250) NOT NULL, `group_des` blob, `members` blob, `timestamp` datetime NOT NULL, `on_duty` blob, `leader` blob, PRIMARY KEY (`group_name`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8
Then execute the command, the code generating model.py
python manage.py inspectdb
Model.py generated code as follows
class AlarmGroup(models.Model): group_name = models.CharField(primary_key=True, max_length=250) group_des = models.TextField(blank=True, null=True) members = models.TextField(blank=True, null=True) timestamp = models.DateTimeField()class Meta:
managed = False
db_table = 'alarm_group'
There's db_table mapping table name in the database.