django从零开始-模型
1.设置统计表
配置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('events 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) # 创建时间(自动获取当前时间) class Meta: unique_together = ('phone', 'event') def __str__(self): return self.realname # 修改创建时间类型 # ALTER TABLE `sign_event` CHANGE `create_time` `create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP # ALTER TABLE `sign_guest` CHANGE `create_time` `create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
2.后台管理-编辑admin.py
from django.contrib import admin from sign.models import * # Register your models here. class EventAdmin(admin.ModelAdmin): list_display = ['name', 'status', 'start_time','id'] search_fields = ['name'] # 搜索功能 list_filter = ['status'] # 过滤器 class GuestAdmin(admin.ModelAdmin): list_display = ['realname', 'phone','email','sign','create_time','event_id'] list_display_links = ('realname', 'phone') # 显示链接 search_fields = ['realname','phone'] # 搜索功能 list_filter = ['event_id'] # 过滤器 admin.site.register(Event, EventAdmin) admin.site.register(Guest, GuestAdmin)
3.数据访问
- python manage.py shell 进入shell命令行进行数据操作
- 插入数据 data= Event() data.save()
- 查询数据
- 删除数据
- 更新数据
4.配置mysql数据库
编辑setting.py
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST':'127.0.0.1', 'PORT':'3306', 'NAME':'guest', 'USER':'root', 'PASSWORD':'123456', 'OPTIONS': { 'init_command':"SET sql_mode = 'STRICT_TRANS_TABLES'", } } }