新建djando的配置
一 :新建django的配置
准备工作,先在数据库中创建一个库,并指定utf8编码
CREATE DATABASE IF NOT EXISTS student default character set utf8 COLLATE utf8_general_ci;
在项目下的settings.py配置文件下配置数据库
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'student', 'USER': 'root', 'PASSWORD': '123123', 'HOST': '192.168.244.10', 'PORT': '3306', }
}
__init__.py文件的配置
import pymysql pymysql.install_as_MySQLdb() #打开数据库链接 db = pymysql.connect("192.168.244.10","root","123123","student") #使用cursor()方法获取游标 cursor = db.cursor() cursor.execute("SELECT VERSION()") data = cursor.fetchone() print("Database version : %s" % data) db.close()
测试一下和数据库的连通性
python manage.py runserver
完了以后先退出终端,先不启动
***************************************
二 .创建一个应用,并激活
python manage.py startapp myApp
创建项目后在settings.py文件中添加项目
激活其实就是这一步的添加过程
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myApp'
在模板中定义和数据表相对应的类
class Grades(models.Model): gname = models.CharField(max_length=20) gdate = models.DateField() ggirlnum = models.IntegerField() gboynum = models.IntegerField() isDelete = models.BooleanField(default=False) def __str__(self): return "%s-%d-%d" %(self.gname,self.ggirlnum,self.gboynum) class Student(models.Model): sname = models.CharField(max_length=20) sgender = models.BooleanField(default=True) sage = models.IntegerField() scontend = models.CharField(max_length=20) isDelete = models.BooleanField(default=False) sgrade = models.ForeignKey("Grades",on_delete=models.CASCADE)
在数据库中生成数据表:
要在数据库中生成数据,先要生成一个迁移文件,并执行迁移文件
创建上面的应用myApp后,会在myApp下生成migrations目录
python manage.py makemigrations
python manage.py migrate
三 :在终端测试模板和数据库交互的情况(创建数据)
进入django的shell环境 E:\老男孩课程\tudent>python manage.py shell ########################################### >>> from myApp.models import Grades,Student >>> from django.utils import timezone >>> from datetime import *
from myApp.models import Grades,Student
from django.utils import timezone
from datetime import *
----------------------------------------------------- 通过模型类查看数据 >>> Grades.objects.all()
Grades.objects.all()
------------------------------------------------------ 添加一条数据的本质 本质:创建一个模型类的对象 >>> grade1 = Grades() >>> grade1.gname = "python04" >>> grade1.gdate = datetime(year=2017,month=11,day=17) >>> grade1.ggirlnum = 3 >>> grade1.gboynum = 70 >>> grade1.save()
grade1 = Grades()
grade1.gname = "python04"
grade1.gdate = datetime(year=2017,month=11,day=17)
grade1.ggirlnum = 3
grade1.gboynum = 70
grade1.save()
----------------------------------------------------------------------------------------------
>>> grade2 = Grades()
>>> grade2.gname = "python05"
>>>
>>>
>>> grade2.gdate = datetime(year=2017,month=11,day=30)
>>> grade2.ggirlnum = 8
>>> grage2.gboynum = 66
>>> grade2.gboynum = 72
>>> grade2.save()
grade2 = Grades()
grade2.gname = "python05"
grade2.gdate = datetime(year=2017,month=11,day=30)
grade2.ggirlnum = 8
grade2.gboynum = 66
grade2.gboynum = 72
grade2.save()
----------------------------------------------------------------------------------
四 :在shell环境查看生成的表数据(包括修改和删除数据)
退出重新进一次shell环境
quit() python manage.py shell #并重新导入三个库 >>> from myApp.models import Grades,Student >>> from django.utils import timezone >>> from datetime import * 通过模型类查看数据 >>> Grades.objects.all()
查看单个表中的数据
>>> Grades.objects.get(pk=1)
<Grades: python04-3-70>
>>> Grades.objects.get(pk=2)
<Grades: python05-8-72>
修改单个表中的数据
语法:模型对象.gboynum=值
>>> grade2.gboynum = 50
>>> grade2.save()
删除单个表中的数据(物理删除)
语法:模型对象.delete()
>>> grade2.delete()
(1, {'myApp.Student': 0, 'myApp.Grades': 1})
获得关联对象的集合
先创建两个学生表
>>> grade1=Grades.objects.get(pk=1) >>> stu1 = Student() >>> stu1.sname = "王福田" >>> stu1.sgender = False >>> stu1.sage = 25
#如下,指点班级列等于另外一个表的对象,就会自动关联 >>> stu1.sgrade = grade1 >>> stu1.save()
grade1=Grades.objects.get(pk=1)
stu1 = Student()
stu1.sname = "王福田"
stu1.sgender = False
stu1.sage = 25
stu1.sgrade = grade1
stu1.save()
---------------------------------------------------------
>>> stu2 = Student() >>> stu2.sname = "张宝来" >>> stu2.sgender = False >>> stu2.sage = 30 >>> stu2.sgrade = grade1 >>> stu2.save()
stu2 = Student()
stu2.sname = "张宝来"
stu2.sgender = False
stu2.sage = 30
stu2.sgrade = grade1
stu2.save()
----------------------------------------------
查看班级有哪些学生:
因为没有重写类的return,所以返回的不是数据
另外,_set.all是django自带的一个方法,虽然我没有定义,但是也可以使用
>>> grade1.student_set.all()
<QuerySet [<Student: Student object (1)>, <Student: Student object (2)>]>
>>>
一条命令创建学生并关联主键
不用save,直接存入数据库
>>> stu3=grade1.student_set.create(sname=u'zhangsan',scontend=u'my name is zhangsan',sage=45)
在maApp文件夹下的models.py文件中编写一个函数,用于返回数据值
class Grades(models.Model): gname = models.CharField(max_length=20) gdate = models.DateField() ggirlnum = models.IntegerField() gboynum = models.IntegerField() isDelete = models.BooleanField(default=False) def __str__(self): return "%s-%d-%d" %(self.gname,self.ggirlnum,self.gboynum)
五 .启动服务器
python manage.py runserver ip:port 如果是本机可以不写,默认是本机ip,端口是8000 python manage.py runserver
五. 站点管理
在另外一个终端,创建超用户
python manage.py createsuperuser
在setting.py文件中修改字符集和时间
LANGUAGE_CODE = 'zh-Hans' TIME_ZONE = 'Asia/Shanghai'
管理数据表
在admin.py文件中对表进行注册
注册以后刷新http://127.0.0.1:8000/admin/页面,会出现已经注册上的表
from .models import Grades,Student #注册 admin.site.register(Grades) admin.site.register(Student)
5.1 站点自定义管理
在应用的admin.py文件中定义
from .models import Grades,Student class GradesAdmin(admin.ModelAdmin): #列表页属性 list_display = ['gname','gdate','ggirlnum','gboynum','isDelete'] # list_filter = ['gname'] # search_fields = [] # list_per_page = []
class StudentAdmin(admin.ModelAdmin):
list_display = ['sname','sgender','sage','sgrade','isDelete','scontend']
list_per_page = 2
#添加,修改列表也属性
#可以规定先后顺寻,
#这两个属性不能同时使用
# fields =['ggirlnum','gboynum','gdate','isDelete']
# fieldsets = [
# ("num",{"fields":['ggirlnum','gboynum']}),
# ("base",{"fields":['gname','gdate','isDelete']})
# ]
admin.site.register(Grades,GradesAdmin) #要点,这个后面怎加了GradesAdmin,否则上面的属性不会用到 admin.site.register(Student)
admin.site.register(Student,StudentAdmin)
5.2 小需求练习
在原来的admin.py配置文件中加入StudentInfo类,并在GradeAdmin类中加入inlines属性
class StudentInfo(admin.TabularInline): #使用模板中的哪个类 model = Student #自动添加几个 extra = 2 class GradesAdmin(admin.ModelAdmin): inlines = [StudentInfo] #列表页属性 list_display = ['gname','gdate','ggirlnum','gboynum','isDelete'] #过滤条件 list_filter = ['gname'] #搜索字段 search_fields = ['gname'] #分页 # list_per_page = 2
5.3布尔值的显示问题
男女显示的问题
class StudentAdmin(admin.ModelAdmin): def gender(self): if self.sgender: return "男" else: return "女"
#设置页面列的名称
gender.short_description = "性别"
list_display = ['pk','sname','gender','sage','sgrade','isDelete','scontend'] list_per_page = 10
5.4执行动作的位置问题(action的问题)
class StudentAdmin(admin.ModelAdmin): # def gender(self): # if self.sgender: # return "男" # else: # return "女" #设置页面列的名称 # gender.short_description = "性别" #就是设置action的布尔值 actions_on_bottom = True actions_on_top = False list_display = ['pk','sname','gender','sage','sgrade','isDelete','scontend'] list_per_page = 10 admin.site.register(Grades,GradesAdmin) admin.site.register(Student,StudentAdmin)
5.5使用装饰器完成注册
以后都用装饰器来完成注册
@admin.register(Student)
class StudentAdmin(admin.ModelAdmin): # def gender(self): # if self.sgender: # return "男" # else: # return "女" #设置页面列的名称 # gender.short_description = "性别" #就是设置action的布尔值 actions_on_bottom = True actions_on_top = False list_display = ['pk','sname','gender','sage','sgrade','isDelete','scontend'] list_per_page = 10
把调用注释掉
#admin.site.register(Student,StudentAdmin)
六,视图
视图其实就是一个函数,在创建的app中的vews.py文件中添加
from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("sunck is a good man")
按照django架构,http请求过来是先找url,url在找视图,所以我们这里先配置url控制器
urls.py文件默认在项目student目录下,除此之外,我们需要在新建的应用myApp目录中也建一个urls.py文件,所以总共加起来有两个urls.py文件
这里我们先配置默认已经存在的urls.py文件
from django.contrib import admin from django.conf.urls import include,url urlpatterns = [ url(r'admin/', admin.site.urls), url(r'^',include('myApp.urls')), ]
接下来修改刚创建的myApp文件下的urls.py文件
from django.conf.urls import url from . import views urlpatterns = [ url (r'^$', views.index) ]
七,模板
模板是html页面
根据视图中传递过来啦的数据,进行填充
7.1创建模板目录
在templates目录下创建目录,templates和myApp,student,manage,py都是同级的
在templates目录下创建对应的应用的目录
7.2配置模板路径
在settings.py文件
其中basedir指的就是myApp,student,manage,py这几个所在的文件夹的目录
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
7.3小需求练习,我要展示http://172.0.0.1:8000/grade
先定义模板,我的html长什么样
在templates下的myApp下新建一个html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>班级</title> </head> <body> <h1> {% for grade in grades%} <li> <a href="#">{{ grade.gname }}</a> </li> {% endfor %} </h1> </body> </html>
7.3.1模板语法;
语法1:{{输出值,可以是变量,也可以是对象.属性}}
语法2:{%代码段%}
7.3.2, 定义视图
视图从模板中取数据
from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("sunck is a good man") from .models import Grades def grades(request): #去模板里取数据 gradesList=Grades.objects.all() #将数据传递给模板,模板再渲染页面,将渲染好的页面返回给浏览器,下面字典里的grades就是html中的变量 return render(request,'myApp/grades.html',{"grades":gradesList})
7.3.3 设置url,
浏览器通过url来找视图
因为上面最外层的url已经包含了应用层的url,所以直接在最里面的urls.py文件中配置视图
from django.conf.urls import url from . import views urlpatterns = [ url (r'^$', views.index), #如果没有视图,则要导入 url(r'^grades/$',views.grades) ]
7.4 小需求,在原来的基础上,展示班级下面的所有学生
定义视图
from .models import Student def students(request): studentsList=Student.objects.all() return render(request,'myApp/student.html',{"students":studentsList}) def gradesStudents(request,num): #获得对应的班级对象 grade=Grades.objects.get(pk=num) #获得班级下的所有学生 studentsList = grade.student_set.all() return render(request,'myApp/student.html',{"students":studentsList})
添加url
from django.conf.urls import url from . import views urlpatterns = [ url (r'^$', views.index), #如果没有视图,则要导入 url(r'^grades/$',views.grades), url(r'students/$',views.students), url(r'^grades/(\d+)$',views.gradesStudents) ]
创建学生的模板
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>学生信息</title> </head> <body> <h1> <ul> {% for student in students %} <li> {{ student.sname }}--{{ students.scontend }} </li> {% endfor %} </ul> </h1> </body> </html>
同时修改班级的模板
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>班级</title> </head> <body> <h1> {% for grade in grades%} <li> <a href="{{ grade.id }}">{{ grade.gname }}</a> </li> {% endfor %} </h1> </body> </html>
八:移动数据库以后,删除迁移文件,在生成一次迁移文件,再执行
ll
九。补充,ORM映射关系
O:模型 R:映射 M:数据库
十.模型类,属性,表,字段的关系
一个模型类在数据库中对应一张表,模型类的属性在与之对应的表中对应一个字段
模型类中的属性
学习链接:https://blog.csdn.net/qq_34493908/article/details/80388041
十一,创建模型管理器
先修改模型类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.db import models # Create your models here. class Grades(models.Model): gname = models.CharField(max_length=20) gdate = models.DateField() ggirlnum = models.IntegerField() gboynum = models.IntegerField() isDelete = models.BooleanField(default=False) def __str__(self): return "%s-%d-%d" % (self.gname, self.ggirlnum, self.gboynum) class Meta(): db_table = "grades" class Student(models.Model): sname = models.CharField(max_length=20) sgender = models.BooleanField(default=True) sage = models.IntegerField() scontend = models.CharField(max_length=20) isDelete = models.BooleanField(default=False) sgrade = models.ForeignKey("Grades", on_delete=models.CASCADE) def __str__(self): return self.sname lastTime = models.DateTimeField(auto_now=True) creatTime = models.DateTimeField(auto_now_add=True) #定义模型中的元选项 class Meta: db_table = "student" ordering = ['id']
再准备数据,重新迁移一次数据
insert into grades(gname,gdate,ggirlnum,gboynum,isDelete) values("python01","2018-2-3",22,34,0), ("python02","2018-2-2",27,34,0), ("python03","2018-2-30",22,34,0), ("python04","2018-2-30",22,34,0); ------------------------------- insert into student(sname,sgender,scontend,isDelete,sgrade_id,sage,lastTime,creatTime) values("薛延美",1,"薛延美",0,4,20,"2018-2-3","2018-2-3"), ("王占山",1,"我叫网站山",0,4,20,"2018-2-3","2018-2-3"), ("李婷",1,"我叫李婷",0,4,20,"2018-2-3","2018-2-3"), ("赵本山",1,"我叫赵本山",0,4,20,"2018-2-3","2018-2-3"), ("刘大河",1,"我叫刘大河",0,4,20,"2018-2-3","2018-2-3"), ("刘德华",1,"我叫刘德华",0,4,20,"2018-2-3","2018-2-3");