Django数据库创建与查询及ORM的概念

ORM:是封装在pymysql上层的文件。他的作用是把python语句转换成sql语句,从而去数据库里操作数据。
从数据库里获得的数据,经过orm转换为对象,对象可以直接调用属性获得值。orm本质是个中转站。


上节课查漏及本节课内容

python3解释器需要在app下面的__init__导入pymysql pymysql....
python2不需要 python3不支持

数据库存入数据的时候要注意重启和不重启的区别

dbsqlite 小型数据库 测试用 不用链接

中途不能切数据库,比如sqlite和mysql 对待数据库需慎重

用orm对数据进行操作 不要在navicate数据库里直接改


return的是对象

wsgiref被封装到源码里了

细看:
render模板文件open 接受参数:request,模板文件,传一个字典(去模板里替换),拿到模板的字符串,HttpResponse传给浏览器
redirect 返回一个url地址给浏览器

template下面建文件夹

static 如果用元组一定要加逗号,不然会直接报错

static前面加/原因是前面有http//:127.0.0.1:8000

app下面可以建文件写方法,在views里面调用

request里面请求体,请求头都在里面,被django封装

作业需要注意的地方:如果模板里有重复的name值,会把两个name值放到列表里,取值的时候默认取后面的值。
还有一个就是urls里面



今日内容:
orm能干的事:
1 创建表,修改表,删除表
2 插入数据
3 修改数据
4 删除数据
不能干:不能创建数据库


类名-----》表

对象实例------》一条数据

属性-----》字段


使用mysql步骤:
0 创建数据库(orm不能创建数据库)
1 在settings里配置
2 在app的init.py文件里写上:import pymysql
pymysql.install_as_MySQLdb()
3 在models里定义类,类必须继承 models.Model
4 写属性,对应着数据库的字段
5 执行 python manage.py makemigrations(相当于做一个记录)
6 执行 pyhton manage.py migrate (会把记录执行到数据库)

创建出来的表名是app的名字_类名

下面是在课件上进行了详细的注释内容,重要的我基本都标注了

这里连接的是mysql数据库,sqlite用起来不习惯
  1 """
  2 Django settings for day03 project.
  3 
  4 Generated by 'django-admin startproject' using Django 1.11.
  5 
  6 For more information on this file, see
  7 https://docs.djangoproject.com/en/1.11/topics/settings/
  8 
  9 For the full list of settings and their values, see
 10 https://docs.djangoproject.com/en/1.11/ref/settings/
 11 """
 12 
 13 import os
 14 
 15 # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
 16 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 17 
 18 
 19 # Quick-start development settings - unsuitable for production
 20 # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
 21 
 22 # SECURITY WARNING: keep the secret key used in production secret!
 23 SECRET_KEY = '8a7#ap_9gk93+=kup84ig@6std%hgmhj*kruml5*78kkkw=ar3'
 24 
 25 # SECURITY WARNING: don't run with debug turned on in production!
 26 DEBUG = True
 27 
 28 ALLOWED_HOSTS = []
 29 
 30 
 31 # Application definition
 32 
 33 INSTALLED_APPS = [
 34     'django.contrib.admin',
 35     'django.contrib.auth',
 36     'django.contrib.contenttypes',
 37     'django.contrib.sessions',
 38     'django.contrib.messages',
 39     'django.contrib.staticfiles',
 40     'app01.apps.App01Config', # 每创建一个app都要放到里面
 41 ]
 42 
 43 MIDDLEWARE = [
 44     'django.middleware.security.SecurityMiddleware',
 45     'django.contrib.sessions.middleware.SessionMiddleware',
 46     'django.middleware.common.CommonMiddleware',
 47     # 'django.middleware.csrf.CsrfViewMiddleware',
 48     'django.contrib.auth.middleware.AuthenticationMiddleware',
 49     'django.contrib.messages.middleware.MessageMiddleware',
 50     'django.middleware.clickjacking.XFrameOptionsMiddleware',
 51 ]
 52 
 53 ROOT_URLCONF = 'day03.urls'
 54 
 55 TEMPLATES = [
 56     {
 57         'BACKEND': 'django.template.backends.django.DjangoTemplates',
 58         'DIRS': [os.path.join(BASE_DIR, 'templates')]  # 没有需要自己手动添加
 59         ,
 60         'APP_DIRS': True,
 61         'OPTIONS': {
 62             'context_processors': [
 63                 'django.template.context_processors.debug',
 64                 'django.template.context_processors.request',
 65                 'django.contrib.auth.context_processors.auth',
 66                 'django.contrib.messages.context_processors.messages',
 67             ],
 68         },
 69     },
 70 ]
 71 
 72 WSGI_APPLICATION = 'day03.wsgi.application'
 73 
 74 
 75 # Database
 76 # https://docs.djangoproject.com/en/1.11/ref/settings/#databases
 77 
 78 
 79 # 数据库之间怎么切换?(正式项目中是不允许中间切换数据库的)
 80 DATABASES = {
 81     # 'default': {
 82     #     'ENGINE': 'django.db.backends.sqlite3',
 83     #     'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
 84     # }
 85     # 连接mysql需要加入用户名 密码 数据库名字 IP+PORT  五个重要对象
 86     # 下面是连接mysql需要填写的
 87     'default': {
 88         'ENGINE': 'django.db.backends.mysql',
 89         'HOST':'127.0.0.1',
 90         'PORT':3306,
 91         'USER':'root',
 92         "PASSWORD":'123',
 93         'NAME': 'test',
 94     #     'ATOMIC_REQUEST': True,
 95     # 设置为True统一http请求对应的所有sql都放在一个事务中执行(要么所有都成功,要么所有都失败,失败了执行回滚操作)。
 96     # 是全局性的配置, 如果要对某个http请求放水(然后自定义事务),可以用non_atomic_requests修饰器
 97          }
 98 }
 99 
100 
101 # Password validation
102 # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
103 
104 # 验证密码???
105 AUTH_PASSWORD_VALIDATORS = [
106     {
107         'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
108     },
109     {
110         'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
111     },
112     {
113         'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
114     },
115     {
116         'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
117     },
118 ]
119 
120 
121 # Internationalization
122 # https://docs.djangoproject.com/en/1.11/topics/i18n/
123 
124 LANGUAGE_CODE = 'en-us'
125 
126 TIME_ZONE = 'UTC'
127 
128 USE_I18N = True
129 
130 USE_L10N = True
131 
132 USE_TZ = True
133 
134 
135 # Static files (CSS, JavaScript, Images)
136 # https://docs.djangoproject.com/en/1.11/howto/static-files/
137 
138 STATIC_URL = '/static/'
139 STATICFILES_DIRS = [
140     os.path.join(BASE_DIR,'static')
141     ]
settings

 

app下面的__init__文件

1 import pymysql
2 pymysql.install_as_MySQLdb()
3 
4 # 这是因为django默认你导入的驱动是MySQLdb,可是MySQLdb 对于py3有很大问题,所以我们需要的驱动是PyMySQL
5 # 所以,我们只需要找到项目名文件下的__init__,在里面写入上面的
__init__

 

视图层函数

 1 from django.shortcuts import render, HttpResponse
 2 from app01.models import *
 3 
 4 # orm不能指定字符编码  如遇到字符编码问题去终端或者navicate改
 5 # 创建数据库记得要先设定字符编码
 6 # Create your views here.
 7 def register(request):
 8     if request.method == 'POST':
 9         # request.POST请求体的内容都在里面,并且是一个字典的形式
10         name = request.POST.get('name')
11         password = request.POST.get('password')
12         gender = request.POST.get('gender')
13         birthday = request.POST.get('birthday')
14         # 第一种方式
15         # user=UserInfo(birthday=birthday,name=name,password=password,gender=gender)
16         # user.save()
17         # 第二种方式(推荐这种)创建成功,会返回一个对象
18         # 里面的参数是关键字参数,必须要关键字传参
19         user = UserInfo.objects.create(birthday=birthday, name=name, password=password, gender=gender)
20         print(user)
21         return HttpResponse('注册成功')
22 
23     return render(request, 'register.html')
24 
25 
26 def user_list(request):
27     # 把数据表里用户全拿回来
28     user_list = UserInfo.objects.all()
29     # print(type(user_list))
30     #     # print(user_list[0].name)
31     #     # print(user_list[0].password)
32     # user_list是orm自定义的一个类型  queryset 形似列表,里面是一个个对象(表里的一行数据组成一个对象,可以通过对象.字段进行取值)
33     return render(request, 'user_list.html', {'user_list': user_list})
views

 

models

 1 from django.db import models
 2 # models里面存放类  类继承models模块中的Model类
 3 
 4 # Create your models here.
 5 
 6 # models是模块名 Model是模块里的类方法
 7 class UserInfo(models.Model):  # 类名即数据库的表名
 8     # 注意:models后面跟着的都是作者自定义的类名
 9     # 等号前面的是数据库中的字段,也是一个python中的实例对象。
10     nid = models.AutoField(primary_key=True)  # 自增长并且设置为键唯一 primary_key = True 设置id为主键
11     name = models.CharField(max_length=32)  # max_length = 32 设置name最大长度为32
12     password=models.CharField(max_length=32,null=True)  # 设置密码最大长度为32 且允许为空(设置的默认为空,新加的字段)
13     # 删除一个字段就是直接注释掉models的类中代码,再刷进去
14     # 添加一个字段就是直接用migrations刷进去,然后选择2退出在models类中设置默认值,有下面两种,注意区分
15     # default='' 默认值
16     # null=True 字段可以为空
17     gender = models.IntegerField()  # int类型 用0或1代表男还是女
18     birthday = models.DateField()  # 日期类型的对象
19     # user_datil=models.OneToOneField(to='User_datil',to_field='nid')
20     # dd=models.ForeignKey(to='dd',to_field='nid')
21     #
22     # sss=models.ManyToManyField(to='author')
23 
24     def __str__(self):
25         return self.name
models

 

user_list模板

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>用户信息</title>
 6 </head>
 7 <body>
 8 
 9 
10 <table border="1">
11     <thead>
12     <tr>
13         <th>id</th>
14         <th>用户名</th>
15         <th>密码</th>
16         <th>性别</th>
17         <th>生日</th>
18     </tr>
19     </thead>
20     <tbody>
21     {% for user in user_list %}
22         <tr>
23 {#        对象直接调用字段名称可获得对应的值#}
24             <td>{{ user.nid }}</td>
25             <td>{{ user.name }}</td>
26             <td>{{ user.password }}</td>
27             <td>{{ user.gender }}</td>
28             <td>{{ user.birthday }}</td>
29         </tr>
30 
31     {% endfor %}
32 
33 
34 
35     </tbody>
36 </table>
37 
38 </body>
39 </html>
user_list

 

posted @ 2018-08-31 15:39  Roc_Atlantis  阅读(478)  评论(0编辑  收藏  举报