上一部分给大家介绍Django的视图。
接下来继续来了解Django框架,来看第三部分,此部分是对数据库的操作。
目录:
一、设计系统表
- 四、Django配置MySQL
一、设计系统表 返回目录
首先打开sign/models.py,通过模型完成标的创建:
from django.db import models # Create your models here. # 发布会表
class Event(models.Model): name = models.CharField(max_length=100) # 发布会标题
limit = models.IntegerField() # 参加人数
status = models.BooleanField() # 状态
address = models.CharField(max_length=200) # 地址
start_time = models.DateTimeField("event time") # 发布会时间
create_time = models.DateTimeField(auto_now=True) # 创建时间(自动获取当前时间) def __str__(self):
return self.name # 嘉宾表
class Guest(models.Model): event = models.ForeignKey(Event) # 关联发布会id
realname = models.CharField(max_length=64) # 姓名
phone = models.CharField(max_length=16) # 手机号
email = models.EmailField() # 邮箱
sign = models.BooleanField() # 签到状态
create_time = models.DateTimeField(auto_now=True) # 创建时间(自动获取当前时间)
def __str__(self):
return self.realname
class Meta: unique_together = ("event","phone")
模型创建好后,进行数据迁移:
打开终端执行:
test:guest zhan$ python manage.py makemigrations sign
Migrations for 'sign':
sign/migrations/0001_initial.py:
- Create model Event
- Create model Guest
test:guest zhan$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, sign
Running migrations:
Applying sign.0001_initial... OK
sign/migrations/下会生成0001_initial.py文件:
二、admin后台管理 返回目录
首先,在sign/admin.py文件中写入:
from django.contrib import admin
from sign.models import Event,Guest # Register your models here.
# 这些代码通知Admin管理工具为这些模块提供界面
admin.site.register(Event)
admin.site.register(Guest)
如下图:
登录Admin后台系统:http://127.0.0.1:8000/admin/
添加发布会:
列表显示一列发布会名字,是因为自己定义了__str__():里面的name
如果想显示全部的列表字段,则在 sign/admin.py中继续添加:
from django.contrib import admin
from sign.models import Event,Guest # Register your models here.
# 添加两个方法,把字段值放在list_display中
class EventAdmin(admin.ModelAdmin):
list_display = ["id","name","limit","status","address","start_time","create_time"] class GuestAdmin(admin.ModelAdmin):
list_display = ["event","realname","phone","email","sign","create_time"] # 这些代码通知Admin管理工具为这些模块提供界面
admin.site.register(Event,EventAdmin) # 并添加class进来
admin.site.register(Guest,GuestAdmin)
还可以添加【搜索栏、过滤器】,在sign/admin.py中继续添加:
from django.contrib import admin
from sign.models import Event,Guest # Register your models here. class EventAdmin(admin.ModelAdmin):
list_display = ["id","name","limit","status","address","start_time","create_time"]
search_fields = ["name"] # 搜索栏
list_filter = ["status"] # 过滤器 class GuestAdmin(admin.ModelAdmin):
list_display = ["event","realname","phone","email","sign","create_time"]
search_fields = ["realname","phone"] # 搜索栏
list_filter = ["sign"] # 过滤器 # 这些代码通知Admin管理工具为这些模块提供界面
admin.site.register(Event,EventAdmin)
admin.site.register(Guest,GuestAdmin)
search_fields:用于创建搜索栏,可以设置匹配多个关键字。
list_filter:用于创建字段过滤器。
三、基本数据访问(SQLite数据库) 返回目录
下面我们通过Django自带的SQLite操作数据库,如何通过数据库进行操作呢,需要命令行运行manage.py的shell命令
python manage.py shell
1、插入语句
# 准备条件
>>> from sign.models import Event,Guest
>>> from datetime import datetime
>>> Event.objects.all()
<QuerySet [<Event: 小米发布会>]>
>>> Guest.objects.all()
<QuerySet [<Guest: zc>]>
①第一种插入语句:创建和保存
insert_e1 = Event(id='2',
name='魅族发布会',
limit='1000',
status=True,
address='天津梅江会展',
start_time=datetime(2018,10,15,12,0,0)) insert_e1.save()
②第二种插入语句:直接创建
Event.objects.create(id='2',
name='魅族发布会',
limit='1000',
status=True,
address='天津梅江会展',
start_time=datetime(2018,10,15,12,0,0))
Guest.objects.create(realname='owen',
phone= '136',
email='136@qq.com',
sign=False,
event_id='2')
但是会提示警告信息:
1430: RuntimeWarning: DateTimeField Event.start_time received a naive datetime (2018-10-15 12:00:00) while time zone support is active.
RuntimeWarning)
UTC问题,可以忽略此问题,guest/settings.py中,设置USE_TZ = False。
2、查询语句
(1)精确查询
address作为查询条件,查询name
>>> e1 = Event.objects.get(address = '天津梅江会展')
>>> e1.name
'魅族发布会'
# 或者
>>> Event.objects.get(address = '天津梅江会展').name
'魅族发布会'
>>>
相对应的Guest表:
>>> g1 = Guest.objects.get(realname__contains='ow')
>>> g1.event
<Event: 魅族发布会>
>>> g1.event.name
'魅族发布会'
>>> g1.event.address
'天津梅江会展'
>>>
(2)模糊查询
只想查询关键字
filter()方法是从数据库中取得匹配结果,返回的是列表;name与contains双下划线连接,contains类似于LIKE语句。
>>> Event.objects.filter(name__contains='发布会')
<QuerySet [<Event: 小米发布会>, <Event: 魅族发布会>]>
>>>
(3)删除数据
注:我写的是模糊查询删除,最好是精确删除。
>>> g1 = Guest.objects.get(realname__contains='ow')
>>> g1.delete()
(1, {'sign.Guest': 1})
>>> # 或者
>>> Guest.objects.get(realname__contains='ow').delete()
(1, {'sign.Guest': 1})
>>>
(4)更新数据
>>> g1 = Guest.objects.get(realname__contains='ow')
>>> g1.realname='owen02'
>>> g1.save()
>>> # 或者 Guest.objects.select_for_update().filter(realname__contains='ow').update(realname='owen')
1
四、Django配置MySQL 返回目录
虽然SQLite数据库可以操作数据,但是不适用于大型项目,下面来介绍MySQL数据库在Django中的操作。
1、安装Mysql数据库
参考我的另一篇文章:《【Mac系统 + Mysql】之安装Mysql数据库》
2、MySQL数据库基本操作
数据库操作:
# 进入mysql
mysql -u root -p
# 查看数据库
show databases; # 创建数据库
create database if not exists guest; # 进入guest数据库
use guest; # 查看数据库的表
show tables; # 创建表
create table if not exists sign_guest(
id int unsigned auto_increment,
realname varchar(100)not null,
phone varchar(16) not null,
email VARCHAR(20) UNIQUE, # UNIQUE:不可重复,只有null是可以重复
sign varchar(5),
create_time date,
primary key(id,phone)
)charset=utf8; # 查看表属性
desc sign_guest; # 插入数据
insert into sign_guest(realname,phone,email,sign,create_time)values
('zc','','123@qq.com','',now())
3、安装pymysql
安装命令:
pip install pymysql
具体操作可参考我的文章:《【Python + Mysql】之用pymysql库连接Mysql数据库并进行增删改查操作》
在此忽略......
4、在Django中配置MySQL
修改guest/settings.py下的DATABASES
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 驱动
'HOST': '127.0.0.1', # 主机地址
'PORT': '', # 端口号
'NAME': 'guest', # 数据库
'USER': 'root', # 登录用户名
'PASSWORD': '', # 登录密码
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
},
}
}
在guest项目中输入命令:
test:guest zhan$ python manage.py migrate
但是报错:
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'
原因为没有MySQLdb驱动,解决办法如下:
在.../guest/__init__.py中添加代码:
import pymysql pymysql.install_as_MySQLdb()
然后再执行命令:
python manage.py migrate
但是,会提示错误,如果没有问题跳过此段落:
......
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying sessions.0001_initial... OK
Applying sign.0001_initial...Traceback (most recent call last):
...
...
...
pymysql.err.InternalError: (1050, "Table 'sign_guest' already exists")
原因为我在上面写mysql基本数据库操作时候,自己创建了sign_guest表,所以最好删除guest数据库,重新再执行一遍命令。
终端进入数据库,具体操作不描述,上面基本操作介绍过。
# 删除数据库
drop database guest; # 创建数据库
create database guest;
再执行命令:
python manage.py migrate
正确显示如下:
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, sign
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying sessions.0001_initial... OK
Applying sign.0001_initial... OK
因为更换了数据库,所以里面的Admin超级管理员账号也需要重新创建。
然后再终端输入命令:
python manage.py createsuperuser
Username (leave blank to use 'zhan'): admin
Email address: xxx@xxx.com
Password:
Password (again):
Superuser created successfully.
至此,Django的模型创建完毕,下一篇介绍Django模板