zoukankan      html  css  js  c++  java
  • Django web框架-----Django连接本地现有mysql数据库

    • 第一步:win10下载mysql5.7压缩包配置安装mysql,创建数据库或导入数据库
    • 第二步:win10搭建django2.1.7开发环境,创建项目为mytestsite,创建应用app为quicktool
    • 第三步:编辑与项目同名的文件夹的配置文件(mytestsite/settings.py),配置数据库信息
    DATABASES = {
        'default': {
            # 'ENGINE': 'django.db.backends.sqlite3',
            # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
              'ENGINE':'django.db.backends.mysql',
              'NAME':'数据库名称',
              'USER':'数据库账号',
              'PASSWORD':'数据库密码',
              'HOST':'数据库地址,本地的话即为localhost',
              'PORT':'数据库端口,默认为3306',
        }
    }
    
    • 第四步:编辑与项目同名的文件夹的__init__.py文件(mytestsite/__init__.py),引入mysql数据库
    import pymysql
    pymysql.install_as_MySQLdb()
    
    • 第五步:在项目的manage.py所在路径下使用命令
    python manage.py inspectdb  >  D:django_testmytestsitequicktoolmodels.py 
    

    集成已有的数据库和应用,生成models,复制到应用app的models.py中(quicktool/models.py)

    命令行结束返回无报错即成功,quicktool的models.py 文件会自动复制生成本地环境已有数据库的类,类名为数据表名,继承自models.Model,每个类定义有数据表内的字段名

    报错:django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.3 or newer is required; you have 0.7.11.None

    解决:找到Python安装路径下的的Python37Libsite-packagesdjangodbackendsmysqlase.py文件,将文件中的如下代码注释

    if version < (1, 3, 3):
    raise ImproperlyConfigured("mysqlclient 1.3.3 or newer is required; you have %s" % Database.__version__)

    报错:File "C:UsersAdministratorAppDataLocalProgramsPythonPython37libsite-packagesdjangodbackendsmysqloperations.py", line 146, in last_executed_query

    query = query.decode(errors='replace')
    AttributeError: 'str' object has no attribute 'decode'

    解决:找到所在文件代码行,将decode改为encode即可

    • 第六步:使用Django shell查询数据表并返回结果

    在项目的manage.py所在路径下使用命令 python manage.py shell

    报以下错误信息:
    AssertionError: Model quicktool.AppVersionInfo can't have more than one AutoField.

    原因是:第五步复制导入的数据库的部分表里增加了AutoField列,但是又不指定这个列作为主键,全文搜索应用app的models.py文件出现models.AutoField()的地方,为django的AutoField字段设定为主键models.AutoField(primary_key=True)即可解决
    再继续使用以下命令行查询数据

    python manage.py shell
    from quicktool.models import AppVersionInfo
    AppVersionInfo.objects.get(version_code=10)
    

    数据库里有表AppVersionInfo和字段version_code

    CREATE TABLE `app_version_info` (version_code` int(3) NOT NULL DEFAULT '0')
    

    查询结果打印的是id值,并没有显示出具体相关数据表的信息

    在quicktool/models.py文件中的每个类增加以下代码即可解决打印问题

    def __str__(self):
        # 在Python3中使用  def __unicode__(self):
        return self.url
    

    新增方法后,打印的是数据表的具体数据

    • 第七步:将查询的结果可视化到网页上

    quicktool/views.py文件:

    from django.http import HttpResponse
    from quicktool.models import AppVersionInfo
    def index(request):
        appl = AppVersionInfo.objects.get(version_code=25)
        return HttpResponse(str(appl))
    

    mytestsite/mytestsite/urls.py文件的路径,其余省略:

    from quicktool import views as quicktool_views   # 新增
    urlpatterns = [
        path('', quicktool_views.index, name='home'),  # 新增
    ]
    

    quicktool/templates/home.html文件的body,其余省略:

    <body>
    {{ appl }}
    </body>
    

    查询结果可视化显示在网页,显示如下:

  • 相关阅读:
    Fiddler: Creation of interception certificate failed.
    ip地址检查正则表达式 兼容ipv4,ipv6
    母版页与子页的启动过程
    erlang 读取confg文件异常 could not start kernel pid error in config file
    转义字符 显示形式 转换成 实际形式 \\n to \n
    How to use epoll? A complete example in C
    Lex & Flex 词法分析器实践(未完,持续更新)
    我理解的爱情———柳智宇 (转载)
    Learning by doing 系列文章概述
    锁与RCU数据共享机制
  • 原文地址:https://www.cnblogs.com/kristin/p/10791358.html
Copyright © 2011-2022 走看看