python学习之第十四天补充

本节内容

学员管理系统练习

Django ORM操作进阶

用户认证

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

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

项目需求:

1.分讲师\学员\课程顾问角色,2.学员可以属于多个班级,学员成绩按课程分别统计3.每个班级至少包含一个或多个讲师4.一个学员要有状态转化的过程 ,比如未报名前,报名后,毕业老学员5.客户要有咨询纪录, 后续的定期跟踪纪录也要保存6.每个学员的所有上课出勤情况\学习成绩都要保存7.学校可以有分校区,默认每个校区的员工只能查看和管理自己校区的学员8.客户咨询要区分来源

 学员管理系统表结构

常用ORM操作

 示例models

创建


1

2

3

>>> from blog.models import Blog

>>> b = Blog(name=‘Beatles Blog‘, tagline=‘All the latest Beatles news.‘)

>>> b.save()

This performs an INSERT SQL statement behind the scenes. Django doesn’t hit the database until you explicitly call save().

The save() method has no return value.

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

ForeignKey的关联


1

2

3

4

5

>>> 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关联  


1

2

3

>>> from blog.models import Author

>>> joe = Author.objects.create(name="Joe")

>>> entry.authors.add(joe)

添加多个ManyToMany对象


1

2

3

4

5

>>> 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)

查询

 单表内查询语句

 关联查询

对同一表内不同的字段进行对比查询,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:


1

2

>>> 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 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:


1

>>> 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:


1

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

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:


1

2

>>> from datetime import timedelta

>>> Entry.objects.filter(mod_date__gt=F(‘pub_date‘+ timedelta(days=3))

Caching and QuerySets

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 QuerySets correctly. For example, the following will create two QuerySets, evaluate them, and throw them away:


1

2

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

>>> print([e.pub_date for 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 Entry may have been added or deleted in the split second between the two requests.

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


1

2

3

>>> queryset = Entry.objects.all()

>>> print([p.headline for in queryset]) # Evaluate the query set.

>>> print([p.pub_date for in queryset]) # Re-use the cache from the evaluation.

When QuerySets 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:


1

2

3

>>> 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:


1

2

3

4

>>> 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 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.

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 Q object encapsulates a single LIKE query:


1

2

from django.db.models import Q

Q(question__startswith=‘What‘)

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

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


1

Q(question__startswith=‘Who‘) | Q(question__startswith=‘What‘)

This is equivalent to the following SQL WHERE clause:


1

WHERE question LIKE ‘Who%‘ OR question LIKE ‘What%‘

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


1

Q(question__startswith=‘Who‘) | ~Q(pub_date__year=2005)

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 Q object arguments to a lookup function, the arguments will be “AND”ed together. For example:


1

2

3

4

Poll.objects.get(

    Q(question__startswith=‘Who‘),

    Q(pub_date=date(200552)) | Q(pub_date=date(200556))

)

... 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 Q objects and keyword arguments. All arguments provided to a lookup function (be they keyword arguments or Q objects) are “AND”ed together. However, if a Q object is provided, it must precede the definition of any keyword arguments. For example:


1

2

3

Poll.objects.get(

    Q(pub_date=date(200552)) | Q(pub_date=date(200556)),

    question__startswith=‘Who‘)

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


1

2

3

4

# INVALID QUERY

Poll.objects.get(

    question__startswith=‘Who‘,

    Q(pub_date=date(200552)) | Q(pub_date=date(200556)))

... would not be valid.

  

更新 

Updating multiple objects at once


1

2

# Update all the headlines with pub_date in 2007.

Entry.objects.filter(pub_date__year=2007).update(headline=‘Everything is the same‘)

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

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:


1

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

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:


1

2

# THIS WILL RAISE A FieldError

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

Aggregation(聚合)

 示例models

 常用聚合场景需求

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

  

  

  

用户认证 


1

2

3

4

5

6

7

8

9

10

11

from django.contrib.auth import authenticate

user = authenticate(username=‘john‘, password=‘secret‘)

if user is not None:

    # the password verified for the user

    if user.is_active:

        print("User is valid, active and authenticated")

    else:

        print("The password is valid, but the account has been disabled!")

else:

    # the authentication system was unable to verify the username and password

    print("The username and password were incorrect.")

How to log a user out?


1

2

3

4

5

from django.contrib.auth import logout

def logout_view(request):

    logout(request)

    # Redirect to a success page.

分类: Python自动化开发之路

时间: 2024-11-03 03:28:57

python学习之第十四天补充的相关文章

python学习之第十四天再补充

自定义template tags 中间件 CRSF 权限管理 分页 Django分页 https://docs.djangoproject.com/en/1.9/topics/pagination/ 自定义template tags https://docs.djangoproject.com/es/1.9/howto/custom-template-tags/ 权限管理 django 自带有基本的权限管理 ,但粒度和限制权限的维度都只是针对具体的表,如果我们想根据业务功能来限制权限,那就得自己

Python学习笔记(十四)

一.序列化与反序列化 Python 中的 pickle模块提供了一种序列化对象的方法 import pickle class Student(object): def __init__(self,name,age,school="新华") self.__name = name self.__age = age self.__school = school def get_dict(slef): return { "name":self.__name, "a

python学习笔记-(十四)进程&协程

一. 进程 1. 多进程multiprocessing multiprocessing包是Python中的多进程管理包,是一个跨平台版本的多进程模块.与threading.Thread类似,它可以利用multiprocessing.Process对象来创建一个进程.该进程可以运行在Python程序内部编写的函数.该Process对象与Thread对象的用法类似. 创建一个Process实例,可用start()方法启动. join()方法可以等待子进程结束后再继续往下运行,通常用于进程间的同步.

Python学习笔记(十四)安装第三方模块

摘抄:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143186362353505516c5d4e38456fb225c18cc5b54ffb000 本文章完全用来个人复习使用,侵删: 在Python中,安装第三方模块,是通过包管理工具pip完成的. 在命令提示符窗口下尝试运行pip,如果Windows提示未找到命令,可以重新运行安装程序添加pip. 注意:Mac或Lin

Python 学习笔记(十四)Python类(三)

完善类的内容 示例: 1 #! /usr/bin/env python 2 # coding =utf-8 3 4 #通常类名首字母大写 5 class Person(object): 6 7 """ 8 This is about a person #类文档 9 """ 10 11 def __init__(self,name,lang="python"):#初始化函数,类被实例化的时候,要执行 12 self.name =

python学习(二十四)开发接口

模拟一些接口,在接口没有开发成功前,可以用它来测试 用来查询数据 1.第一个接口 import flask,json #__name__,代表当前这个python文件 server=flask.Flask(__name__) #把这个python文件,当做一个服务 #ip:8000/index?uge @server.route('/index',methods=['get','post']) #可以只写一个,那就只支持那一个 def index(): res={'msg':'这是开发的第一个接

python学习第七十四天:单表查询

单表查询 创建表 创建模型 在models.py中定义类,一个类就是一张表 from django.db import models class Book(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=64) pub_data = models.DateField() price = models.DecimalField(max_digits=5, decima

Python学习日记(三十四) Mysql数据库篇 二

外键(Foreign Key) 如果今天有一张表上面有很多职务的信息 我们可以通过使用外键的方式去将两张表产生关联 这样的好处能够节省空间,比方说你今天的职务名称很长,在一张表中就要重复的去写这个职务的名字,很浪费空间;除此之外也能起到一个约束的作用. 像department就是外键. 执行代码: create table t1( uid bigint auto_increment primary key, name varchar(32), department_id int, gender

python学习第五十四天:作用域对象与运用技巧

1. JS作用域 1.1 全局作用域和局部作用域 函数外面声明的就是 全局作用域 函数内是局部作用域 全局变量可以直接在函数内修改和使用 变量,使用var是声明,没有var是使用变量. 如果在函数内使用var来声明变量,在函数内会覆盖同名的全局变量 1.2 变量提升 在变量声明之前 去使用变量 会得到 undefined ,而不是报错 函数内,如果声明了跟全局变量同名的局部变量, 在声明之前使用改变量,得到undefined( 该变量已经是局部的啦) 1.3 作用域链 当一个作用域 使用某个变量