虽然django适合从零开始构建一个项目,但有时候整合原有的数据库也在所难免,下面以django整合我的mysql作说明。
mysql数据是我从京东上抓取的数据,数据表名为jd,演示如图
下面将jd整合到django中,操作如下
1.修改settings.py
root@iZ28b5osxspZ:/home/jd#vim jd/settings.py
...
DATABASES={'default': {'ENGINE': 'django.db.backends.mysql',#'NAME': os.path.join(BASE_DIR, "jd.sql"),
'NAME':'jd','HOST':'127.0.0.1','PORT':3306,'USER':'root','PASSWORD':'hehe',
}
}
...
2.针对已有数据库自省生成新的models
root@iZ28b5osxspZ:/home/jd#python manage.py inspectdb#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.#▽#You'll have to do the following manually to clean this up:#Also note: You'll have to insert the output of 'django-admin.py sqlcustom [app_label]'#into your database.
from __future__ importunicode_literalsfrom django.db importmodelsclassJd(models.Model):
▽
id= models.IntegerField(primary_key=True) #AutoField?
▽
category= models.CharField(max_length=64, blank=True)
▽#* Make sure each model has one field with primary_key=True
name = models.CharField(max_length=128, blank=True)
price= models.CharField(max_length=64, blank=True)
url= models.CharField(max_length=64, blank=True)classMeta:
managed=False
db_table= 'jd'root@iZ28b5osxspZ:/home/jd#
3.导出模型并代替models.py
root@iZ28b5osxspZ:/home/jd#python manage.py inspectdb > models.py
root@iZ28b5osxspZ:/home/jd#ls
jd main manage.py models.py
root@iZ28b5osxspZ:/home/jd#mv models.py main/
4.默认配置下生成不可修改/删除的models,修改meta class中的managed=True则告诉django可以对数据库进行操作
root@iZ28b5osxspZ:/home/jd#python manage.py migrate
Operations to perform:
Apply all migrations: admin, contenttypes, auth, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying sessions.0001_initial... OK
root@iZ28b5osxspZ:/home/jd#python manage.py shell
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
Type"copyright", "credits" or "license" formore information.
IPython1.2.1 --An enhanced Interactive Python.
?-> Introduction and overview of IPython's features.
%quickref ->Quick reference.
help-> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
5.是不是真的可以操作原有数据库了呢?进行验证即可
root@iZ28b5osxspZ:/home/jd#python manage.py shell
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
Type"copyright", "credits" or "license" formore information.
IPython1.2.1 --An enhanced Interactive Python.
?-> Introduction and overview of IPython's features.
%quickref ->Quick reference.
help-> Python's own help system.
object? -> Details about 'object', use 'object??' forextra details.In [1]: from main.models importJd
In [2]: Jd.objects.all()
Out[2]: [, , , , , , , , , , , , , , , , , , , , '...(remaining elements truncated)...']