Django系列4:數據常規操做級聯數據

#PPT html

#Mysql使用python

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

安裝pymysql mysql

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中git

import pymysql
pymysql.install_as_MySQLdb()

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

##解決方法 仍然使用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文件:sql

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.pyshell

from django.conf.urls import url

from Three import views

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

##views.pydjango

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.htmlsession

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

<h2>Three Index</h2>

{{ student_name }}

</body>
</html>

#定義模型 app

python shell

#關聯(學生-班級) ##model.py

from django.db import models

# Create your models here.
class Grade(models.Model):
    g_name = models.CharField(max_length=32)




class Student(models.Model):
    s_name = models.CharField(max_length=16)

    # django 升級到2.0以後,表與表之間關聯的時候,必需要寫on_delete參數,不然會報異常:
    # TypeError: init() missing 1 required positional argument: ‘on_delete’
    s_grade = models.ForeignKey(Grade,on_delete=models.CASCADE)

'''
    on_delete=None,               # 刪除關聯表中的數據時,當前表與其關聯的field的行爲
	on_delete=models.CASCADE,     # 刪除關聯數據,與之關聯也刪除
	on_delete=models.DO_NOTHING,  # 刪除關聯數據,什麼也不作
	on_delete=models.PROTECT,     # 刪除關聯數據,引起錯誤ProtectedError
	# models.ForeignKey('關聯表', on_delete=models.SET_NULL, blank=True, null=True)
	on_delete=models.SET_NULL,    # 刪除關聯數據,與之關聯的值設置爲null(前提FK字段須要設置爲可空,一對一同理)
	# models.ForeignKey('關聯表', on_delete=models.SET_DEFAULT, default='默認值')
	on_delete=models.SET_DEFAULT, # 刪除關聯數據,與之關聯的值設置爲默認值(前提FK字段須要設置默認值,一對一同理)
	on_delete=models.SET,         # 刪除關聯數據,
	 a. 與之關聯的值設置爲指定值,設置:models.SET(值)
	 b. 與之關聯的值設置爲可執行對象的返回值,設置:models.SET(可執行對象)
'''

##DDL python magange.py makemigrations, migrate

-- auto-generated definition
create table Three_grade
(
  id     int auto_increment
    primary key,
  g_name varchar(32) not null
);


create table Three_student
(
  id         int auto_increment
    primary key,
  s_name     varchar(16) not null,
  s_grade_id int         not null,
  constraint Three_student_s_grade_id_ffbb8485_fk_Three_grade_id
  foreign key (s_grade_id) references hellodjango.Three_grade (id)
);

##Three->>templates-->student_three_list.html

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

<ul>
    {% for student in students %}
    <li>{{ student.s_name }}</li>
    {% endfor %}
    
</ul>

</body>
</html>

##views.html

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

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

from Three.models import Student, Grade


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)

#多獲取1
def get_grade(request):

    student = Student.objects.get(pk=1)
    grade= student.s_grade


    return HttpResponse("Grade %s",grade.g_name)


 #一獲取多
def get_students(request):

    grade = Grade.objects.get(pk=1)

    students = grade.student_set.all()

    context = {
        "students":students
    }
    return render(request, "students_three_list.html", context=context)
相關文章
相關標籤/搜索