Django模型
一、设计系统表
Django提供了完善的模型层来创建和存取数据,它包含所存储数据的必要字段和行为。通常每个模型对应数据库中唯一的一张表,所以,模型避免了我们直接对数据库操作。
Django模型基本知识:
- 每个模型是一个python类,继承django.db.models.Model类。
- 该模型的每个属性表示一个数据库字段
- 所有这一切,已经给了你一个自动生成数据库访问的API
打开/sign/models.py 文件,通过模型完成表的创建。
from django.db import models # Create your models here. #发布会表 from django.db import models 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 = ('event','phone') def __str__(self): return self.realname
当模型创建好后,执行数据库迁移。
C:\Users\solo\guest>python3 manage.py makemigrations sign Migrations for 'sign': sign\migrations\0001_initial.py: - Create model Article - Create model Event - Create model Guest
C:\Users\solo\guest>python3 manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, sign
Running migrations:
Applying sign.0001_initial... OK
admin 后台管理
创建发布会和嘉宾表同样可以通过Admin后台管理
打开/sign/admin.py文件
admin.py
from django.contrib import admin from sign.models import Event,Guest admin.site.register(Event) admin.site.register(Guest)
这些代码通知Admin管理工具为这些模块提供界面
登陆admin后台。
显示更多字段:
修改admin.py
from django.contrib import admin from sign.models import Event,Guest # admin.site.register(Event) # admin.site.register(Guest) # Register your models here. class EventAdmin(admin.ModelAdmin): list_display = ['id','name','status','address','start_time'] class GuestAdmin(admin.ModelAdmin): list_display = ['realname','phone','email','sign','create_time','event'] admin.site.register(Event,EventAdmin) admin.site.register(Guest,GuestAdmin)
快速生成过滤器和搜索栏:
from django.contrib import admin from sign.models import Event,Guest # admin.site.register(Event) # admin.site.register(Guest) # 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'] search_fields = ['realname','phone'] #搜索栏 list_filter = ['sign'] #过滤器 admin.site.register(Event,EventAdmin) admin.site.register(Guest,GuestAdmin)
search_field用于创建表字段的搜索器,可以设置搜索关键字匹配多个表字段。
list_filter用于创建字段过滤器。