django根據數據表生成模型inspectdb

python manage.py inspectdb >polls/models.py

 

inspectdb簡單介紹
具體用法,在Django項目下
python manage.py inspecdb > [your app name]\models.py
1
作用
衆所周知,Django較爲適合原生開發,即通過該框架搭建一個全新的項目,通過在修改models.py來創建新的數據庫表。但是往往有時候,我們需要利用到之前的已經設計好的數據庫,數據庫中提供了設計好的多種表單。那麼這時如果我們再通過models.py再來設計就會浪費很多的時間。所幸Django爲我們提供了inspecdb的方法。他的作用即使根據已經存在對的mysql數據庫表來反向映射結構到models.py中.
inspectdb使用步驟
通過配置settings文件以及__init__.py來連接到本地的mysql數據庫。(之前的博客有談到方法)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'second_shop',
        'USER':'root',
        'PASSWORD':'123',
        'HOST':'127.0.0.1',
        'PORT':'3306',
    }
}
1
2
3
4
5
6
7
8
9
10
在terminal中執行語句
python manage.py inspectdb > [your app name]\models.py
1
查看models.py代碼
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
#   * Rearrange models' order
#   * Make sure each model has one field with primary_key=True
#   * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
#
# Also note: You'll have to insert the output of 'django-admin sqlcustom [app_label]'
# into your database.
from __future__ import unicode_literals

from django.db import models


class Good(models.Model):
    good_name = models.CharField(max_length=255, blank=True, null=True)
    good_price = models.DecimalField(max_digits=10, decimal_places=0, blank=True, null=True)
    good_days = models.IntegerField(max_length=10, blank=True)
    good_id = models.CharField(max_length=18, blank=True)

    class Meta:
        managed = False
        # False表示在遷移時候不新建此表,所以這裏應該改爲TRUE
        db_table = 'good'
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章