Python之路,Day15 - Django适当进阶篇
Python之路,Day15 - Django适当进阶篇
本节内容
学员管理系统练习
Django ORM操作进阶
用户认证
Django练习小项目:学员管理系统设计开发
带着项目需求学习是最有趣和效率最高的,今天就来基于下面的需求来继续学习Django
项目需求:
1.分讲师\学员\课程顾问角色,
2.学员可以属于多个班级,学员成绩按课程分别统计
3.每个班级至少包含一个或多个讲师
4.一个学员要有状态转化的过程 ,比如未报名前,报名后,毕业老学员
5.客户要有咨询纪录, 后续的定期跟踪纪录也要保存
6.每个学员的所有上课出勤情况\学习成绩都要保存
7.学校可以有分校区,默认每个校区的员工只能查看和管理自己校区的学员
8.客户咨询要区分来源
#This example retrieves all Entry objects with a Blog whose name is 'Beatles Blog': Entry.objects.filter(blog__name='Beatles Blog') Blog.objects.filter(entry__headline__contains='Lennon')
对同一表内不同的字段进行对比查询,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 F expressions
to allow such comparisons. Instances of
F()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
F()object to reference the pingback count, and use that
F()object in the query:
Django supports the use of addition, subtraction, multiplication, division, modulo, and power arithmetic with
F()objects, both with constants and with other
F()objects. To find all the blog entries with more than twice as many comments as pingbacks, we modify the query:
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:
For date and date/time fields, you can add or subtract a timedelta
object. The following would return all entries that were modified more than 3 days after they were published:
Caching and QuerySet
s
Each QuerySet
contains a cache to minimize database access. Understanding how it works will allow you to write the most efficient code.
In a newly created QuerySet
, the cache is empty. The first time a QuerySet
is evaluated – and, hence, a database query happens – Django saves the query results in the QuerySet
’s cache and returns the results that have been explicitly requested (e.g., the next element, if the QuerySet
is being iterated over). Subsequent evaluations of the QuerySet
reuse the cached results.
Keep this caching behavior in mind, because it may bite you if you don’t use your QuerySet
s correctly. For example, the following will create two QuerySet
s, evaluate them, and throw them away:
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
Entrymay have been added or deleted in the split second between the two requests.
To avoid this problem, simply save the QuerySet
and reuse it:
When QuerySet
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 limiting the querysetusing 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:
However, if the entire queryset has already been evaluated, the cache will be checked instead:
Complex lookups with Q
objects(复杂查询)
Keyword argument queries – in filter()
, etc. – are “AND”ed together. If you need to execute more complex queries (for example, queries with OR
statements), you can use Q objects
.
A Q object
(
django.db.models.Q) is an object used to encapsulate a collection of keyword arguments. These keyword arguments are specified as in “Field lookups” above.
For example, this
Qobject encapsulates a single
LIKEquery:
Qobjects can be combined using the
&and
|operators. When an operator is used on two
Qobjects, it yields a new
Qobject.
For example, this statement yields a single
Qobject that represents the “OR” of two
"question__startswith"queries:
This is equivalent to the following SQL
WHEREclause:
You can compose statements of arbitrary complexity by combining
Qobjects with the
&and
|operators and use parenthetical grouping. Also,
Qobjects can be negated using the
~operator, allowing for combined lookups that combine both a normal query and a negated (
NOT) query:
Each lookup function that takes keyword-arguments (e.g. filter()
, exclude()
, get()
) can also be passed one or more
Qobjects as positional (not-named) arguments. If you provide multiple
Qobject arguments to a lookup function, the arguments will be “AND”ed together. For example:
... roughly translates into the SQL:
SELECT * from polls WHERE question LIKE 'Who%' AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
Lookup functions can mix the use of
Qobjects and keyword arguments. All arguments provided to a lookup function (be they keyword arguments or
Qobjects) are “AND”ed together. However, if a
Qobject 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 F expressions
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:
However, unlike
F()objects in filter and exclude clauses, you can’t introduce joins when you use
F()objects in an update – you can only reference fields local to the model being updated. If you attempt to introduce a join with an
F()object, a
FieldErrorwill be raised:
Aggregation(聚合)
# Total number of books. >>> Book.objects.count() 2452 # Total number of books with publisher=BaloneyPress >>> Book.objects.filter(publisher__name='BaloneyPress').count() 73 # Average price across all books. >>> from django.db.models import Avg >>> Book.objects.all().aggregate(Avg('price')) {'price__avg': 34.35} # Max price across all books. >>> from django.db.models import Max >>> Book.objects.all().aggregate(Max('price')) {'price__max': Decimal('81.20')} # Cost per page >>> Book.objects.all().aggregate( ... price_per_page=Sum(F('price')/F('pages'), output_field=FloatField())) {'price_per_page': 0.4470664529184653} # All the following queries involve traversing the Book<->Publisher # foreign key relationship backwards. # Each publisher, each with a count of books as a "num_books" attribute. >>> from django.db.models import Count >>> pubs = Publisher.objects.annotate(num_books=Count('book')) >>> pubs [<Publisher BaloneyPress>, <Publisher SalamiPress>, ...] >>> pubs[0].num_books 73 # The top 5 publishers, in order by number of books. >>> pubs = Publisher.objects.annotate(num_books=Count('book')).order_by('-num_books')[:5] >>> pubs[0].num_books 1323
更多聚合查询例子:https://docs.djangoproject.com/en/1.9/topics/db/aggregation/
用户认证
How to log a user out¶
关注 - 0
粉丝 - 639 +加关注 0 0 « 上一篇:Python Select 解析 posted @ 2016-05-20 16:29 金角大王 阅读(1165) 评论(0) 编辑 收藏
刷新评论刷新页面返回顶部
- python 自动化之路 day 20 Django进阶/BBS项目【一】
- python小白-day15 Django基础
- Python之路,Day16 - Django 进阶
- python 自动化之路 day 18 前端内容回顾、补充/Django安装、创建
- python 自动化之路 day 08 面向对象进阶
- python2.0_s12_day15_django框架的基本使用
- python 自动化之路 day 19 Django基础[二]
- Python之路【第二十一篇】Django ORM详解
- python 自动化之路 day 07 面向对象基础
- python 自动化之路 day 04.1 python内置函数
- Python进阶(三十六)-Web框架Django项目搭建全过程
- Python+Django+SAE系列教程15-----输出非HTML内容(图片/PDF)
- day15 python随机生成验证码的代码
- python3开发进阶-Django框架的起飞加速一(ORM)
- python进阶15:继承、多态和多重继承
- python之类-django进阶
- PythonDay15
- 复习Python的Day15
- python3开发进阶-Django框架的中间件的五种用法和逻辑过程
- python笔记15--django之web(MVC模式)