Reverse database table database table generated Django ORM inspectdb reverse generation (ii) Django ORM inspectdb

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

Copy the code
# Application definition  
  
INSTALLED_APPS = [  
    'django.contrib.admin',  
    'django.contrib.auth',  
    'django.contrib.contenttypes',  
    'django.contrib.sessions',  
    'django.contrib.messages',  
    'django.contrib.staticfiles',  
    'hello',  
]  
Copy the code

Configuration database in settings.py

Copy the code
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'big_data',
        'USER': 'root',
        'PASSWORD': '1234',
        'HOST': '10.93.84.53',
        'PORT': '3306',
    }
}
Copy the code

 

2, the forward generation

Model.py created in the directory hello app

Copy the code
from django.db import models

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()

Copy the code

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

Copy the code
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
Copy the code

Then execute the command, the code generating model.py

python manage.py inspectdb

Model.py generated code as follows

Copy the code
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'

Copy the code

There's db_table mapping table name in the database.

Guess you like

Origin www.cnblogs.com/python001-vip/p/12606956.html