首页 > 其他 > 详细

Django系列4:数据常规操作级联数据

时间:2020-02-03 23:11:43      阅读:97      评论:0      收藏:0      [点我收藏+]

PPT

技术分享图片
技术分享图片
技术分享图片
技术分享图片

Mysql使用

mysql> create database HelloDjango charset=utf8;
Query OK, 1 row affected (0.01 sec)

技术分享图片

安装pymysql
技术分享图片

pip install pymysql -i https://pypi.douban.com/simple
(venv) MacBookPro:HelloDjango zhangxm$ pip install pymysql
Collecting pymysql
  Downloading https://files.pythonhosted.org/packages/ed/39/15045ae46f2a123019aa968dfcba0396c161c20f855f11dea6796bcaae95/PyMySQL-0.9.3-py2.py3-none-any.whl (47kB)
     |████████████████████████████████| 51kB 196kB/s 
Installing collected packages: pymysql
Successfully installed pymysql-0.9.3
WARNING: You are using pip version 19.3.1; however, version 20.0.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

安装上以后系统仍然是不认这个库的,pymysql伪装成mysqlclient
比较常用的伪装写在程序的__init__.py中

import pymysql
pymysql.install_as_MySQLdb()

Django - installing mysqlclient error: mysqlclient 1.3.13 or newer is required; you have 0.9.3

##解决方法 仍然使用pymysql
1 )配置文件的目录中_init_.py中有如下代码

import pymysql

pymysql.install_as_MySQLdb()    # 这是一个hack,为了在Djano中替代默认的mysqlclient。mysqlclient官方描述:This is a fork of MySQLdb1
2) 点进去install_as_MySQLdb
找到version_info变量,改成

version_info = (1, 3, 13, "final", 0)
3) 改变django.db.backends.mysql.operations.py的一行代码

query = query.decode(errors='replace') -> query = query.encode(errors='replace')
原因:mysqlclient returns bytes object, PyMySQL returns str object
参考:https://github.com/PyMySQL/PyMySQL/issues/790#issuecomment-484201388

技术分享图片

技术分享图片
技术分享图片
技术分享图片
技术分享图片
技术分享图片

python manage.py startapp Three

想要承认项目的存在,更改project settings文件:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'App',
    'Two',
    'Three'
    # 'Three.apps.ThreeConfig' #1.9之后可以这样写

]

然后写Three里的路由规则

新建urls.py

from django.conf.urls import url

from Three import views

urlpatterns = [
    url('^index/', views.index),
]

views.py

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django.template import loader


def index(request):

    three_index = loader.get_template("three_index.html")

    context ={"student_name": '张三'

    }

    #有渲染,解析渲染引擎表达式的作用,如果不需要这些,直接open也可以
    result = three_index.render(context=context)

    print(result)


    return HttpResponse(result)

Three->>templates->>index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Three_Index</title>
</head>
<body>

<h2>Three Index</h2>

{{ student_name }}

</body>
</html>

定义模型

技术分享图片

python shell
技术分享图片

技术分享图片

Django系列4:数据常规操作级联数据

原文:https://www.cnblogs.com/xidianzxm/p/12257952.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!