加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python之路,Day15 - Django适当进阶篇

发布时间:2020-12-17 00:05:55 所属栏目:Python 来源:网络整理
导读:本节内容 学员管理系统练习 Django ORM操作进阶 用户认证 Django练习小项目:学员管理系统设计开发 带着项目需求学习是最有趣和效率最高的,今天就来基于下面的需求来继续学习Django? 项目需求: 1.分讲师学员课程顾问角色,2.学员可以属于多个班级,学员成

本节内容

学员管理系统练习

Django ORM操作进阶

用户认证

Django练习小项目:学员管理系统设计开发

带着项目需求学习是最有趣和效率最高的,今天就来基于下面的需求来继续学习Django?

项目需求:

1.分讲师学员课程顾问角色,2.学员可以属于多个班级,学员成绩按课程分别统计3.每个班级至少包含一个或多个讲师4.一个学员要有状态转化的过程,比如未报名前,报名后,毕业老学员5.客户要有咨询纪录,后续的定期跟踪纪录也要保存6.每个学员的所有上课出勤情况学习成绩都要保存7.学校可以有分校区,默认每个校区的员工只能查看和管理自己校区的学员8.客户咨询要区分来源
django.db <span style="color: #008000;">#<span style="color: #008000;"> Create your models here.
<span style="color: #0000ff;">from
django.core.exceptions <span style="color: #0000ff;">import
<span style="color: #000000;"> ValidationError

<span style="color: #0000ff;">from django.db <span style="color: #0000ff;">import<span style="color: #000000;"> models
<span style="color: #0000ff;">from django.contrib.auth.models <span style="color: #0000ff;">import<span style="color: #000000;"> User

class_type_choices= ((<span style="color: #800000;">'<span style="color: #800000;">online<span style="color: #800000;">',u<span style="color: #800000;">'<span style="color: #800000;">网络班<span style="color: #800000;">'<span style="color: #000000;">),(<span style="color: #800000;">'<span style="color: #800000;">offline_weekend<span style="color: #800000;">',u<span style="color: #800000;">'<span style="color: #800000;">面授班(周末)<span style="color: #800000;">'<span style="color: #000000;">,),(<span style="color: #800000;">'<span style="color: #800000;">offline_fulltime<span style="color: #800000;">',u<span style="color: #800000;">'<span style="color: #800000;">面授班(脱产)<span style="color: #800000;">'<span style="color: #000000;">,)
<span style="color: #0000ff;">class<span style="color: #000000;"> UserProfile(models.Model):
user =<span style="color: #000000;"> models.OneToOneField(User)
name = models.CharField(u<span style="color: #800000;">"<span style="color: #800000;">姓名<span style="color: #800000;">",max_length=32<span style="color: #000000;">)
<span style="color: #0000ff;">def <span style="color: #800080;">unicode<span style="color: #000000;">(self):
<span style="color: #0000ff;">return<span style="color: #000000;"> self.name

<span style="color: #0000ff;">class<span style="color: #000000;"> School(models.Model):
name = models.CharField(u<span style="color: #800000;">"<span style="color: #800000;">校区名称<span style="color: #800000;">",max_length=64,unique=<span style="color: #000000;">True)
addr = models.CharField(u<span style="color: #800000;">"<span style="color: #800000;">地址<span style="color: #800000;">",max_length=128<span style="color: #000000;">)
staffs = models.ManyToManyField(<span style="color: #800000;">'<span style="color: #800000;">UserProfile<span style="color: #800000;">',blank=<span style="color: #000000;">True)
<span style="color: #0000ff;">def <span style="color: #800080;">unicode<span style="color: #000000;">(self):
<span style="color: #0000ff;">return<span style="color: #000000;"> self.name

<span style="color: #0000ff;">class<span style="color: #000000;"> Course(models.Model):
name = models.CharField(u<span style="color: #800000;">"<span style="color: #800000;">课程名称<span style="color: #800000;">",max_length=128,unique=<span style="color: #000000;">True)
price = models.IntegerField(u<span style="color: #800000;">"<span style="color: #800000;">面授价格<span style="color: #800000;">"<span style="color: #000000;">)
online_price = models.IntegerField(u<span style="color: #800000;">"<span style="color: #800000;">网络班价格<span style="color: #800000;">"<span style="color: #000000;">)
brief = models.TextField(u<span style="color: #800000;">"<span style="color: #800000;">课程简介<span style="color: #800000;">"<span style="color: #000000;">)
<span style="color: #0000ff;">def <span style="color: #800080;">unicode<span style="color: #000000;">(self):
<span style="color: #0000ff;">return<span style="color: #000000;"> self.name

<span style="color: #0000ff;">class<span style="color: #000000;"> ClassList(models.Model):
course = models.ForeignKey(<span style="color: #800000;">'<span style="color: #800000;">Course<span style="color: #800000;">'<span style="color: #000000;">)
course_type = models.CharField(u<span style="color: #800000;">"<span style="color: #800000;">课程类型<span style="color: #800000;">",choices=class_type_choices,max_length=32<span style="color: #000000;">)
semester = models.IntegerField(u<span style="color: #800000;">"<span style="color: #800000;">学期<span style="color: #800000;">"<span style="color: #000000;">)
start_date = models.DateField(u<span style="color: #800000;">"<span style="color: #800000;">开班日期<span style="color: #800000;">"<span style="color: #000000;">)
graduate_date = models.DateField(u<span style="color: #800000;">"<span style="color: #800000;">结业日期<span style="color: #800000;">",blank=True,null=<span style="color: #000000;">True)
teachers = models.ManyToManyField(UserProfile,verbose_name=u<span style="color: #800000;">"<span style="color: #800000;">讲师<span style="color: #800000;">"<span style="color: #000000;">)

</span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;def __unicode__(self):</span>
<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;    return "%s(%s)" %(self.course.name,self.course_type)</span>

<span style="color: #0000ff;"&gt;class</span><span style="color: #000000;"&gt; Meta:
    verbose_name </span>= u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;班级列表</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;
    verbose_name_plural </span>= u<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;班级列表</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;
    unique_together </span>= (<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;course</span><span style="color: #800000;"&gt;"</span>,<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;course_type</span><span style="color: #800000;"&gt;"</span>,<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;semester</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;)

<span style="color: #0000ff;">class<span style="color: #000000;"> Customer(models.Model):
qq = models.CharField(u<span style="color: #800000;">"<span style="color: #800000;">QQ号<span style="color: #800000;">",unique=<span style="color: #000000;">True)
name = models.CharField(u<span style="color: #800000;">"<span style="color: #800000;">姓名<span style="color: #800000;">",max_length=32,null=<span style="color: #000000;">True)
phone = models.BigIntegerField(u<span style="color: #800000;">'<span style="color: #800000;">手机号<span style="color: #800000;">',null=<span style="color: #000000;">True)
stu_id = models.CharField(u<span style="color: #800000;">"<span style="color: #800000;">学号<span style="color: #800000;">",null=True,max_length=64<span style="color: #000000;">)
<span style="color: #008000;">#<span style="color: #008000;">id = models.CharField(u"身份证号",max_length=128)
source_type = ((<span style="color: #800000;">'<span style="color: #800000;">qq<span style="color: #800000;">',u<span style="color: #800000;">"<span style="color: #800000;">qq群<span style="color: #800000;">"<span style="color: #000000;">),(<span style="color: #800000;">'<span style="color: #800000;">referral<span style="color: #800000;">',u<span style="color: #800000;">"<span style="color: #800000;">内部转介绍<span style="color: #800000;">"<span style="color: #000000;">),(<span style="color: #800000;">'<span style="color: #800000;">51cto<span style="color: #800000;">',u<span style="color: #800000;">"<span style="color: #800000;">51cto<span style="color: #800000;">"<span style="color: #000000;">),(<span style="color: #800000;">'<span style="color: #800000;">agent<span style="color: #800000;">',u<span style="color: #800000;">"<span style="color: #800000;">招生代理<span style="color: #800000;">"<span style="color: #000000;">),(<span style="color: #800000;">'<span style="color: #800000;">others<span style="color: #800000;">',u<span style="color: #800000;">"<span style="color: #800000;">其它<span style="color: #800000;">"<span style="color: #000000;">),)
source = models.CharField(u<span style="color: #800000;">'<span style="color: #800000;">客户来源<span style="color: #800000;">',choices=source_type,default=<span style="color: #800000;">'<span style="color: #800000;">qq<span style="color: #800000;">'<span style="color: #000000;">)
referral_from = models.ForeignKey(<span style="color: #800000;">'<span style="color: #800000;">self<span style="color: #800000;">',verbose_name=u<span style="color: #800000;">"<span style="color: #800000;">转介绍自学员<span style="color: #800000;">",help_text=u<span style="color: #800000;">"<span style="color: #800000;">若此客户是转介绍自内部学员,请在此处选择内部学员姓名<span style="color: #800000;">",related_name=<span style="color: #800000;">"<span style="color: #800000;">internal_referral<span style="color: #800000;">"<span style="color: #000000;">)

course </span>= models.ForeignKey(Course,verbose_name=u<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;咨询课程</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;)
class_type </span>= models.CharField(u<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;班级类型</span><span style="color: #800000;"&gt;"</span>,choices=<span style="color: #000000;"&gt;class_type_choices)
customer_note </span>= models.TextField(u<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;客户咨询内容详情</span><span style="color: #800000;"&gt;"</span>,help_text=u<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;客户咨询的大概情况,客户个人信息备注等...</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;)
status_choices </span>= ((<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;signed</span><span style="color: #800000;"&gt;'</span>,u<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;已报名</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;),(</span><span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;unregistered</span><span style="color: #800000;"&gt;'</span>,u<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;未报名</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;),(</span><span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;graduated</span><span style="color: #800000;"&gt;'</span>,u<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;已毕业</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;),)

status </span>= models.CharField(u<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;状态</span><span style="color: #800000;"&gt;"</span>,choices=status_choices,default=u<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;unregistered</span><span style="color: #800000;"&gt;"</span>,help_text=u<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;选择客户此时的状态</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;)
consultant </span>= models.ForeignKey(UserProfile,verbose_name=u<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;课程顾问</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;)
date </span>= models.DateField(u<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;咨询日期</span><span style="color: #800000;"&gt;"</span>,auto_now_add=<span style="color: #000000;"&gt;True)

class_list </span>= models.ManyToManyField(<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;ClassList</span><span style="color: #800000;"&gt;'</span>,verbose_name=u<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;已报班级</span><span style="color: #800000;"&gt;"</span>,blank=<span style="color: #000000;"&gt;True)

</span><span style="color: #0000ff;"&gt;def</span> <span style="color: #800080;"&gt;__unicode__</span><span style="color: #000000;"&gt;(self):
    </span><span style="color: #0000ff;"&gt;return</span> <span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;%s,%s</span><span style="color: #800000;"&gt;"</span> %<span style="color: #000000;"&gt;(self.qq,self.name )

<span style="color: #0000ff;">class<span style="color: #000000;"> ConsultRecord(models.Model):
customer = models.ForeignKey(Customer,verbose_name=u<span style="color: #800000;">"<span style="color: #800000;">所咨询客户<span style="color: #800000;">"<span style="color: #000000;">)
note = models.TextField(u<span style="color: #800000;">"<span style="color: #800000;">跟进内容...<span style="color: #800000;">"<span style="color: #000000;">)
status_choices = ((1,u<span style="color: #800000;">"<span style="color: #800000;">近期无报名计划<span style="color: #800000;">"<span style="color: #000000;">),(2,u<span style="color: #800000;">"<span style="color: #800000;">2个月内报名<span style="color: #800000;">"<span style="color: #000000;">),(3,u<span style="color: #800000;">"<span style="color: #800000;">1个月内报名<span style="color: #800000;">"<span style="color: #000000;">),(4,u<span style="color: #800000;">"<span style="color: #800000;">2周内报名<span style="color: #800000;">"<span style="color: #000000;">),(5,u<span style="color: #800000;">"<span style="color: #800000;">1周内报名<span style="color: #800000;">"<span style="color: #000000;">),(6,u<span style="color: #800000;">"<span style="color: #800000;">2天内报名<span style="color: #800000;">"<span style="color: #000000;">),(7,)
status = models.IntegerField(u<span style="color: #800000;">"<span style="color: #800000;">状态<span style="color: #800000;">",help_text=u<span style="color: #800000;">"<span style="color: #800000;">选择客户此时的状态<span style="color: #800000;">"<span style="color: #000000;">)

consultant </span>= models.ForeignKey(UserProfile,verbose_name=u<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;跟踪人</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;)
date </span>= models.DateField(u<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;跟进日期</span><span style="color: #800000;"&gt;"</span>,auto_now_add=<span style="color: #000000;"&gt;True)

</span><span style="color: #0000ff;"&gt;def</span> <span style="color: #800080;"&gt;__unicode__</span><span style="color: #000000;"&gt;(self):
    </span><span style="color: #0000ff;"&gt;return</span> u<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;%s,%s</span><span style="color: #800000;"&gt;"</span> %<span style="color: #000000;"&gt;(self.customer,self.status)

</span><span style="color: #0000ff;"&gt;class</span><span style="color: #000000;"&gt; Meta:
    verbose_name </span>= u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;客户咨询跟进记录</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;
    verbose_name_plural </span>= u<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;客户咨询跟进记录</span><span style="color: #800000;"&gt;"</span>

<span style="color: #0000ff;">class<span style="color: #000000;"> CourseRecord(models.Model):
course = models.ForeignKey(ClassList,verbose_name=u<span style="color: #800000;">"<span style="color: #800000;">班级(课程)<span style="color: #800000;">"<span style="color: #000000;">)
day_num = models.IntegerField(u<span style="color: #800000;">"<span style="color: #800000;">节次<span style="color: #800000;">",help_text=u<span style="color: #800000;">"<span style="color: #800000;">此处填写第几节课或第几天课程...,必须为数字<span style="color: #800000;">"<span style="color: #000000;">)
date = models.DateField(auto_now_add=True,verbose_name=u<span style="color: #800000;">"<span style="color: #800000;">上课日期<span style="color: #800000;">"<span style="color: #000000;">)
teacher = models.ForeignKey(UserProfile,verbose_name=u<span style="color: #800000;">"<span style="color: #800000;">讲师<span style="color: #800000;">"<span style="color: #000000;">)
<span style="color: #0000ff;">def <span style="color: #800080;">unicode<span style="color: #000000;">(self):
<span style="color: #0000ff;">return u<span style="color: #800000;">"<span style="color: #800000;">%s 第%s天<span style="color: #800000;">" %<span style="color: #000000;">(self.course,self.day_num)
<span style="color: #0000ff;">class<span style="color: #000000;"> Meta:
verbose_name = u<span style="color: #800000;">'<span style="color: #800000;">上课纪录<span style="color: #800000;">'<span style="color: #000000;">
verbose_name_plural = u<span style="color: #800000;">"<span style="color: #800000;">上课纪录<span style="color: #800000;">"<span style="color: #000000;">
unique_together = (<span style="color: #800000;">'<span style="color: #800000;">course<span style="color: #800000;">',<span style="color: #800000;">'<span style="color: #800000;">day_num<span style="color: #800000;">'<span style="color: #000000;">)

<span style="color: #0000ff;">class<span style="color: #000000;"> StudyRecord(models.Model):
course_record = models.ForeignKey(CourseRecord,verbose_name=u<span style="color: #800000;">"<span style="color: #800000;">第几天课程<span style="color: #800000;">"<span style="color: #000000;">)
student = models.ForeignKey(Customer,verbose_name=u<span style="color: #800000;">"<span style="color: #800000;">学员<span style="color: #800000;">"<span style="color: #000000;">)
record_choices = ((<span style="color: #800000;">'<span style="color: #800000;">checked<span style="color: #800000;">',u<span style="color: #800000;">"<span style="color: #800000;">已签到<span style="color: #800000;">"<span style="color: #000000;">),(<span style="color: #800000;">'<span style="color: #800000;">late<span style="color: #800000;">',u<span style="color: #800000;">"<span style="color: #800000;">迟到<span style="color: #800000;">"<span style="color: #000000;">),(<span style="color: #800000;">'<span style="color: #800000;">noshow<span style="color: #800000;">',u<span style="color: #800000;">"<span style="color: #800000;">缺勤<span style="color: #800000;">"<span style="color: #000000;">),(<span style="color: #800000;">'<span style="color: #800000;">leave_early<span style="color: #800000;">',u<span style="color: #800000;">"<span style="color: #800000;">早退<span style="color: #800000;">"<span style="color: #000000;">),)
record = models.CharField(u<span style="color: #800000;">"<span style="color: #800000;">上课纪录<span style="color: #800000;">",choices=record_choices,default=<span style="color: #800000;">"<span style="color: #800000;">checked<span style="color: #800000;">",max_length=64<span style="color: #000000;">)
score_choices = ((100,<span style="color: #800000;">'<span style="color: #800000;">A+<span style="color: #800000;">'<span style="color: #000000;">),(90,<span style="color: #800000;">'<span style="color: #800000;">A<span style="color: #800000;">'<span style="color: #000000;">),(85,<span style="color: #800000;">'<span style="color: #800000;">B+<span style="color: #800000;">'<span style="color: #000000;">),(80,<span style="color: #800000;">'<span style="color: #800000;">B<span style="color: #800000;">'<span style="color: #000000;">),(70,<span style="color: #800000;">'<span style="color: #800000;">B-<span style="color: #800000;">'<span style="color: #000000;">),(60,<span style="color: #800000;">'<span style="color: #800000;">C+<span style="color: #800000;">'<span style="color: #000000;">),(50,<span style="color: #800000;">'<span style="color: #800000;">C<span style="color: #800000;">'<span style="color: #000000;">),(40,<span style="color: #800000;">'<span style="color: #800000;">C-<span style="color: #800000;">'<span style="color: #000000;">),(0,<span style="color: #800000;">'<span style="color: #800000;">D<span style="color: #800000;">'<span style="color: #000000;">),(-1,<span style="color: #800000;">'<span style="color: #800000;">N/A<span style="color: #800000;">'<span style="color: #000000;">),(-100,<span style="color: #800000;">'<span style="color: #800000;">COPY<span style="color: #800000;">'<span style="color: #000000;">),(-1000,<span style="color: #800000;">'<span style="color: #800000;">FAIL<span style="color: #800000;">'<span style="color: #000000;">),)
score = models.IntegerField(u<span style="color: #800000;">"<span style="color: #800000;">本节成绩<span style="color: #800000;">",choices=score_choices,default=-1<span style="color: #000000;">)
date = models.DateTimeField(auto_now_add=<span style="color: #000000;">True)
note = models.CharField(u<span style="color: #800000;">"<span style="color: #800000;">备注<span style="color: #800000;">",max_length=255,null=<span style="color: #000000;">True)

</span><span style="color: #0000ff;"&gt;def</span> <span style="color: #800080;"&gt;__unicode__</span><span style="color: #000000;"&gt;(self):
    </span><span style="color: #0000ff;"&gt;return</span> u<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;%s,学员:%s,纪录:%s,成绩:%s</span><span style="color: #800000;"&gt;"</span> %<span style="color: #000000;"&gt;(self.course_record,self.student.name,self.record,self.get_score_display())

</span><span style="color: #0000ff;"&gt;class</span><span style="color: #000000;"&gt; Meta:
    verbose_name </span>= u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;学员学习纪录</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;
    verbose_name_plural </span>= u<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;学员学习纪录</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;
    unique_together </span>= (<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;course_record</span><span style="color: #800000;"&gt;'</span>,<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;student</span><span style="color: #800000;"&gt;'</span>)</pre>

常用ORM操作

django.db name = models.CharField(max_length=100 tagline = (self): name = models.CharField(max_length=50 email = (self): blog = headline = models.CharField(max_length=255 body_text = pub_date = mod_date = authors = n_comments = n_pingbacks = rating = (self): self.headline

创建

>> from blog.models import Blog >>> b = Blog(name='Beatles Blog',tagline='All the latest Beatles news.') >>> b.save()

This performs an??SQL statement behind the scenes. Django doesn’t hit the database until you explicitly call?.

The??method has no return value.

处理带外键关联或多对多关联的对象?

?

>> from blog.models import Entry >>> entry = Entry.objects.get(pk=1) >>> cheese_blog = Blog.objects.get(name="Cheddar Talk") >>> entry.blog = cheese_blog >>> entry.save()

ManyToManyField关联  

>> from blog.models import Author >>> joe = Author.objects.create(name="Joe") >>> entry.authors.add(joe)

添加多个ManyToMany对象

>> john = Author.objects.create(name="John") >>> paul = Author.objects.create(name="Paul") >>> george = Author.objects.create(name="George") >>> ringo = Author.objects.create(name="Ringo") >>> entry.authors.add(john,paul,george,ringo)

查询

all_entries = Entry.objects.all() Entry.objects.filter(pub_date__year=2006) Entry.objects.all().filter(pub_date__year=2006) >>> Entry.objects.filter( ... headline__startswith= ... pub_date__gte= ... pub_date__gte=datetime(2005,1,30 one_entry = Entry.objects.get(pk=1) Entry.objects.all()[:5] Entry.objects.all()[5:10] Entry.objects.order_by()[0] Entry.objects.filter(pub_date__lte=) Entry.objects.get(headline__exact=) Blog.objects.get(name__iexact=) Entry.objects.get(headline__contains=)
Entry.objects.filter(blog__name=Blog.objects.filter(entryheadlinecontains=<span style="color: #800000;">'<span style="color: #800000;">Lennon<span style="color: #800000;">')

对同一表内不同的字段进行对比查询,In the examples given so far,we have constructed filters that compare the value of a model field with a constant. But what if you want to compare the value of a model field with another field on the same model?

Django provides??to allow such comparisons. Instances of??act as a reference to a model field within a query. These references can then be used in query filters to compare the values of two different fields on the same model instance.

For example,to find a list of all blog entries that have had more comments than pingbacks,we construct an??object to reference the pingback count,and use that??object in the query:

>> from django.db.models import F >>> Entry.objects.filter(n_comments__gt=F('n_pingbacks'))

Django supports the use of addition,subtraction,multiplication,division,modulo,and power arithmetic with??objects,both with constants and with other??objects. To find all the blog entries with more than?twice?as many comments as pingbacks,we modify the query:

>> Entry.objects.filter(n_comments__gt=F('n_pingbacks') * 2)

To find all the entries where the rating of the entry is less than the sum of the pingback count and comment count,we would issue the query:

>> Entry.objects.filter(rating__lt=F('n_comments') + F('n_pingbacks'))

For date and date/time fields,you can add or subtract a??object. The following would return all entries that were modified more than 3 days after they were published:

>> from datetime import timedelta >>> Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(days=3))

Caching and?s

Each??contains a cache to minimize database access. Understanding how it works will allow you to write the most efficient code.

In a newly created?,the cache is empty. The first time a??is evaluated – and,hence,a database query happens – Django saves the query results in the?’s cache and returns the results that have been explicitly requested (e.g.,the next element,if the??is being iterated over). Subsequent evaluations of the??reuse the cached results.

Keep this caching behavior in mind,because it may bite you if you don’t use your?s correctly. For example,the following will create two?s,evaluate them,and throw them away:

>> print([e.headline for e in Entry.objects.all()]) >>> print([e.pub_date for e in Entry.objects.all()])

That means the same database query will be executed twice,effectively doubling your database load. Also,there’s a possibility the two lists may not include the same database records,because an??may have been added or deleted in the split second between the two requests.

To avoid this problem,simply save the??and reuse it:

>> queryset = Entry.objects.all() >>> print([p.headline for p in queryset]) # Evaluate the query set. >>> print([p.pub_date for p in queryset]) # Re-use the cache from the evaluation.
When?s are not cached

Querysets do not always cache their results. When evaluating only?part?of the queryset,the cache is checked,but if it is not populated then the items returned by the subsequent query are not cached. Specifically,this means that?using an array slice or an index will not populate the cache.

For example,repeatedly getting a certain index in a queryset object will query the database each time:

>> queryset = Entry.objects.all() >>> print queryset[5] # Queries the database >>> print queryset[5] # Queries the database again

However,if the entire queryset has already been evaluated,the cache will be checked instead:

>> queryset = Entry.objects.all() >>> [entry for entry in queryset] # Queries the database >>> print queryset[5] # Uses cache >>> print queryset[5] # Uses cache

Complex lookups with??objects(复杂查询)

Keyword argument queries – in?,etc. – are “AND”ed together. If you need to execute more complex queries (for example,queries with??statements),you can use?.

A??() is an object used to encapsulate a collection of keyword arguments. These keyword arguments are specified as in “Field lookups” above.

For example,this??object encapsulates a single??query:

?objects can be combined using the??and??operators. When an operator is used on two??objects,it yields a new??object.

For example,this statement yields a single??object that represents the “OR” of two??queries:

This is equivalent to the following SQL??clause:

You can compose statements of arbitrary complexity by combining??objects with the??and??operators and use parenthetical grouping. Also,??objects can be negated using the??operator,allowing for combined lookups that combine both a normal query and a negated () query:

Each lookup function that takes keyword-arguments (e.g.?,?,?) can also be passed one or more?objects as positional (not-named) arguments. If you provide multiple??object arguments to a lookup function,the arguments will be “AND”ed together. For example:

... roughly translates into the SQL:

SELECT * polls WHERE question LIKE = OR pub_date = )

Lookup functions can mix the use of??objects and keyword arguments. All arguments provided to a lookup function (be they keyword arguments or??objects) are “AND”ed together. However,?object is provided,it must precede the definition of any keyword arguments. For example:

... would be a valid query,equivalent to the previous example; but:

... would not be valid.

  

更新 

Updating multiple objects at once

在原有数据的基础上批量自增

Calls to update can also use??to update one field based on the value of another field in the model. This is especially useful for incrementing counters based upon their current value. For example,to increment the pingback count for every entry in the blog:

>> Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)

However,unlike??objects in filter and exclude clauses,you can’t introduce joins when you use??objects in an update – you can only reference fields local to the model being updated. If you attempt to introduce a join with an??object,a?will be raised:

>> Entry.objects.update(headline=F('blog__name'))

?

?

Aggregation(聚合)

django.db name = models.CharField(max_length=100 age = name = models.CharField(max_length=300 num_awards = name = models.CharField(max_length=300 pages = price = models.DecimalField(max_digits=10,decimal_places=2 rating = authors = publisher = pubdate = name = models.CharField(max_length=300 books = registered_users = models.PositiveIntegerField()
>>>2452

<span style="color: #008000;">#<span style="color: #008000;"> Total number of books with publisher=BaloneyPress

Book.objects.filter(publisher__name=<span style="color: #800000;">'<span style="color: #800000;">BaloneyPress<span style="color: #800000;">'<span style="color: #000000;">).count()
73

<span style="color: #008000;">#<span style="color: #008000;"> Average price across all books.

<span style="color: #0000ff;">from django.db.models <span style="color: #0000ff;">import<span style="color: #000000;"> Avg
>>> Book.objects.all().aggregate(Avg(<span style="color: #800000;">'<span style="color: #800000;">price<span style="color: #800000;">'<span style="color: #000000;">))
{<span style="color: #800000;">'<span style="color: #800000;">price__avg<span style="color: #800000;">': 34.35<span style="color: #000000;">}

<span style="color: #008000;">#<span style="color: #008000;"> Max price across all books.

<span style="color: #0000ff;">from django.db.models <span style="color: #0000ff;">import<span style="color: #000000;"> Max
>>> Book.objects.all().aggregate(Max(<span style="color: #800000;">'<span style="color: #800000;">price<span style="color: #800000;">'<span style="color: #000000;">))
{<span style="color: #800000;">'<span style="color: #800000;">price__max<span style="color: #800000;">': Decimal(<span style="color: #800000;">'<span style="color: #800000;">81.20<span style="color: #800000;">'<span style="color: #000000;">)}

<span style="color: #008000;">#<span style="color: #008000;"> Cost per page

<span style="color: #000000;"> Book.objects.all().aggregate(
... price_per_page=Sum(F(<span style="color: #800000;">'<span style="color: #800000;">price<span style="color: #800000;">')/F(<span style="color: #800000;">'<span style="color: #800000;">pages<span style="color: #800000;">'),output_field=<span style="color: #000000;">FloatField()))
{<span style="color: #800000;">'<span style="color: #800000;">price_per_page<span style="color: #800000;">': 0.4470664529184653<span style="color: #000000;">}

<span style="color: #008000;">#<span style="color: #008000;"> All the following queries involve traversing the Book<->Publisher<span style="color: #008000;">

<span style="color: #008000;"> foreign key relationship backwards.

<span style="color: #008000;">#<span style="color: #008000;"> Each publisher,each with a count of books as a "num_books" attribute.

<span style="color: #0000ff;">from django.db.models <span style="color: #0000ff;">import<span style="color: #000000;"> Count
>>> pubs = Publisher.objects.annotate(num_books=Count(<span style="color: #800000;">'<span style="color: #800000;">book<span style="color: #800000;">'<span style="color: #000000;">))
>>><span style="color: #000000;"> pubs
[,<span style="color: #000000;">,...]
>>><span style="color: #000000;"> pubs[0].num_books
73

<span style="color: #008000;">#<span style="color: #008000;"> The top 5 publishers,in order by number of books.

pubs = Publisher.objects.annotate(num_books=Count(<span style="color: #800000;">'<span style="color: #800000;">book<span style="color: #800000;">')).order_by(<span style="color: #800000;">'<span style="color: #800000;">-num_books<span style="color: #800000;">')[:5<span style="color: #000000;">]
>>><span style="color: #000000;"> pubs[0].num_books
1323

更多聚合查询例子:https://docs.djangoproject.com/en/1.9/topics/db/aggregation/?

  

  

  

用户认证 

?

How to log a user out

def logout_view(request):
logout(request)

Redirect to a success page.

  

  

  

  

  

  

  

  

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读