Django操作已有数据库的数据

 

虽然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__ import unicode_literals

from django.db import models


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

    class Meta:
        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可以对数据库进行操作

  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值