django.db.models.Model

model中的每个类就是一张表,类成员变量则是表的字段。

model中字段类型api:

https://docs.djangoproject.com/en/3.1/ref/models/fields/#django.db.models.ForeignKey

django中的model是数据库中的表的,django会根据这些继承了models.Model的类,来生成相应的表,其中可以指定外键,而指定外键的函数中有个参数on_delete,表明被引用的字段被删了之后,该外键如何处理,具体有七种方法,最常见的是on_delete=models.CASCADE,代表删除被引字段的同时,删除该外键。其余处理方式见下链接:

https://stackoverflow.com/questions/38388423/what-does-on-delete-do-on-django-models

django中默认对每个表生成id主键,可以覆写;另外被设为外键的字段会在字段名后添加后缀_id,像上图的外键写法,默认引用Question表中的主键。

python3 manage.py sqlmigrate apps_name migrationsfilenum

e.g

python3 manage.py sqlmigrate polls 0001

python3 manage.py migrate可以执行数据库,代码的更新,而使用sqlmigrate可以直观的看出数据库是如何更新建立的:

model的primary key在django中也可以用pk代替,pk=1,等价于id=1。

django.db.models.F/Q方法

F方法用来获取记录的某个字段的值:

这样可以直接获取这条记录的字段值来更新或者其他作用,而不需要先用order.amount来获取该值。

Q方法是用于复杂查询的:

可在model定义中添加class Meta

views

一个view要返回的内容要么是一个HttpResponse对象,要么是抛出一个异常,例如Http404

template

每一个html就是一个template,我们可以通过使用这些template,并向其传递上下文(template中所需的参数),来返回请求的应答结果。上下文必须是一个字典,其中key是模板中所需要的参数名。

一种返回方法:

return HttpResponse(template.render(context,request))

其中template是一个加载后的模块对象,request是view中的第一个参数

另一种快捷模板返回方法:
return render(request,'polls/index.html',context)

render内部去加载模块并返回一个HttpResponse对象,用于返回给前端。

from django.shortcuts import render

url相关

https://docs.djangoproject.com/en/3.1/topics/http/urls/

include函数

可用于扩展url,传递给其一个URLconf,或者一个二元组;include需要的是一个path对象的列表,来扩展url

url命名空间

有时候不同的app有相同的url后缀,例如polls/detail和anotherpolls/detail,若这两个url都在各自的urlpatterns中用name指定了该url的名字为detail,则在使用名字来代替完整url的地方则会出现二义性,例如在模板中:

该detail不知道是到底是对应哪个url,所以需要对url进行命名空间,隔离同名的url(在此,也可看出在没有使用命名空间前,所有的url的name都是全局的)。

我们可以在app各自的urls.py文件中指定一个变量:app_name,来作为其命名空间的名字:

e.g app_name=polls

则,后续引用该url名字时,则需指定为polls:detail。

HttpRequest类

成员变量

body

请求体的原始字节流数据,一般用在二进制数据处理时。可以用成员函数read,readline进行读取,但一旦使用了这些io读取body后,再去访问该body则会抛RawPostDataException异常。

path

除去域名/ip+端口后的url

Example: "/music/bands/the_beatles/"

method

用于判断是什么类型的请求:

HttpRequest.method=='GET'

HttpRequest.method=='POST' //注意请求类型是大写

GET

当请求为Get请求时,该属性是一个QueryDict对象(类似字典),是Get的参数与其值的字典。

POST

当请求为Post请求时,该属性是一个QueryDict对象(类似字典),是Post的参数与其值的字典。

FILES

若请求中含有文件,则该属性是一个字典,key是文件名,value则是UploadedFile对象。

META

一个描述元数据的字典,要注意在头部中自定义的头部信息,在该字典中对应的键为HTTP_前缀加上原头部名的大写。

headers

这是一个key大小写不敏感的字典,存放着头部的信息

成员函数

get_host()

返回请求的主机名,若没有指定,则为ip+端口

get_port()

返回请求的端口号

get_full_path()

获取成员变量path

is_secure()

若链接为https,则为TRUE

accepts(mime_type)

HttpRequest.accepts('text/html')

True

可用来判断mime的类型。

QueryDict类

django.http.QueryDict

一个类似字典的用来处理一个key对多个value的自定义类。

成员方法

QueryDict实现了所有字典有的方法,因为其是字典的子类。

以下的这些是例外:

QueryDict.init(query_string=None,mutable=False,encoding=None)

通过query_string来实例化一个QD对象:

QueryDict('a=1&a=2&c=3')

<QueryDict: {'a': ['1', '2'], 'c': ['3']}>

大部分QD对象都是不可变的,例如HttpRequest中的GET和POST,如果要可变则在构造时调用mutable=True。

classmethod QueryDict.fromkeys(iterable, value='', mutable=False, encoding=None)

传递一个可迭代的对象,该对象的元素为key的名字,且该QD的每个value均为指定的值:

QueryDict.fromkeys(['a', 'a', 'b'], value='val')

<QueryDict: {'a': ['val', 'val'], 'b': ['val']}>

QueryDict.getitem(key)

获取key的值,该key有多个值,则返回最后一个值,若不存在则抛 django.utils.datastructures.MultiValueDictKeyError异常。

QueryDict.setitem(key,value)

设置key的值,该值是一个列表,表中元素为value;要注意修改的QD必须是一个mutable的,否则不行。

QueryDict.contains(key)

若存在key,则为True

QueryDict.update(other_dict)

传入一个QD或dict对象来更新QD:

q = QueryDict('a=1', mutable=True)

q.update({'a': '2'})

q.getlist('a')

['1', '2']

q['a'] # returns the last

'2'

QueryDict.copy()

深复制,返回一个新的QD对象,新对象是mutable的,即使原QD不可变。

QueryDict.getlist(key, default=None)

获取key对应的list,若key不存在且default指定为None,则为空list。

QueryDict.setlist(key,list_)

设置key的value为指定的list。

QueryDict.appendlist(key, item)

对指定的key对应的list进行append

QueryDict.pop(key)

删除指定的key,并返回其对应的value,若不存在key,则抛出KeyError异常。

q = QueryDict('a=1&a=2&a=3', mutable=True)

q.pop('a')

['1', '2', '3']

QueryDict.popitem()

随机删除一个kv,返回该kv的元组,若为空QD,则抛出KeyError异常。

q = QueryDict('a=1&a=2&a=3', mutable=True)

q.popitem()

('a', ['1', '2', '3'])

QueryDict.items()

返回QD中所有的kv对,但value如果是多个,只返回最后一个,且返回的是一个可迭代对象:

q = QueryDict('a=1&a=2&a=3')

list(q.items())

[('a', '3')]

QueryDict.dict()

返回一个包含QD中所有kv的字典。

QueryDict.values()

返回所有的value,若一个key对应多个value,则返回最后一个值。返回的也是一个可迭代对象

q = QueryDict('a=1&a=2&a=3')

list(q.values())

['3']

QueryDict.lists()

与items一样,也是返回kv对,但对于一对多的情况,lists返回所有key对应的value:

q = QueryDict('a=1&a=2&a=3')

q.lists()

[('a', ['1', '2', '3'])]

HttpResponse

不同于HttpRequest,HttpResponse是编写者负责管理的,而前者是django自动生成的;HttpResponse在django.http模块中。

设置头部字段

添加答复的头部字段,可以像字典的操作一样使用:

response = HttpResponse()
response['Age'] = 120
del response['Age']

不同于dict的点是,如果不存在某个头部字段,使用了del也不会抛异常。

对于想要设置Cache-Control和Vary字段的情况,推荐使用patch_cache_control()和patch_vary_headers(),因为这两个字段一般是有多个用逗号分隔开的值组成的,使用这两个api不会导致中间件添加的信息被覆盖。同时,由于HTTP的头部不允许有换行,如果有换行符例如CR或这LF,则会抛BadHeaderError异常。

告知浏览器把响应当作文件附加物

成员变量

content

一个字节串,代表了相应的内容。

charset

一个字符串,用以标识当前响应使用什么字符集来编码的,若在response对象实例时没有给出,则会从content_type中提取,若提取失败,则使用默认字符集。

status_code

http响应的状态码,例如200,404。。。

reason_phrase

与每个状态码对应的信息,和errmsg相似,若不主动设置,则使用默认的内容。

streaming

默认为false,用于区分streaming response和普通的response

closed

当response已经关闭了,该对象为True

成员方法

init( content=b'', content_type=None, status=200, reason=None, charset=None )

构造函数,用于实例化一个response对象

content可以是一个迭代器,字节串,字符串或者memoryview,其他的类型则会被编码成字节串,迭代器应当返回字符串或字节串。content就是要返给前端的内容。

content_type是MIME type,被用来设置头部中的Content-Type字段,如果没有指定,默认为'text/html; charset=utf-8'

status是http响应码;reason和成员变量reason_phrase同义;charset代表response的内容会按照何种字符集编码。

get(header,alternate=None)

返回指定头部字段的信息,若没有的话,返回alternate

has_header(header)

判断有无指定头部字段,有则True

items()

类似字典的items,返回头部的所有字段kv对。

setdefault(header,value)

设置头部字段的默认值

close()

对于WSGI服务器,需要通过close来关闭连接

write(content)

This method makes an HttpResponse instance a file-like object.

flush()

This method makes an HttpResponseinstance a file-like object.

tell()

This method makes an HttpResponseinstance a file-like object.

getvalue()

返回成员变量content。

下面的几个方法是流式传输,长连接才用的,和websocket类似。

HttpResponse.readable()¶

Always False. This method makes an HttpResponse instance a stream-like object.

HttpResponse.seekable()¶

Always False. This method makes an HttpResponse instance a stream-like object.

HttpResponse.writable()¶

Always True. This method makes an HttpResponse instance a stream-like object.

HttpResponse.writelines(lines)¶

Writes a list of lines to the response. Line separators are not added. This method makes an HttpResponse instance a stream-like object.

Cookie相关成员函数

HttpResponse的子类

django提供了多个HttpResponse的子类来处理不同类型的响应,这些子类都在django.http模块中

  • class HttpResponseRedirect¶

The first argument to the constructor is required – the path to redirect to. This can be a fully qualified URL (e.g. 'https://www.yahoo.com/search/'), an absolute path with no domain (e.g. '/search/'), or even a relative path (e.g. 'search/'). In that last case, the client browser will reconstruct the full URL itself according to the current path. See HttpResponse for other optional constructor arguments. Note that this returns an HTTP status code 302.url¶This read-only attribute represents the URL the response will redirect to (equivalent to the Location response header).

  • class HttpResponsePermanentRedirect¶

Like HttpResponseRedirect, but it returns a permanent redirect (HTTP status code 301) instead of a “found” redirect (status code 302).

  • class HttpResponseNotModified¶

The constructor doesn’t take any arguments and no content should be added to this response. Use this to designate that a page hasn’t been modified since the user’s last request (status code 304).

  • class HttpResponseBadRequest¶

Acts just like HttpResponse but uses a 400 status code.

  • class HttpResponseNotFound¶

Acts just like HttpResponse but uses a 404 status code.

  • class HttpResponseForbidden¶

Acts just like HttpResponse but uses a 403 status code.

  • class HttpResponseNotAllowed¶

Like HttpResponse, but uses a 405 status code. The first argument to the constructor is required: a list of permitted methods (e.g. ['GET', 'POST']).

  • class HttpResponseGone¶

Acts just like HttpResponse but uses a 410 status code.

  • class HttpResponseServerError¶

Acts just like HttpResponse but uses a 500 status code.

JsonResponse对象

class JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, kwargs)

这是一个用json格式编码content的response,因此,其Content-Type头部信息被设置为application/json.

传给data的实参应是一个dict,而如果safe参数指定为False后,data可以为任何可进行Json序列化的对象。若safe为True,但data传了一个非dict,则会抛TypeError错误。

encode参数默认是Json的编码器,一般不需要更改。

StreamingHttpResponse and FileResponse

https://docs.djangoproject.com/en/3.1/ref/request-response/#streaminghttpresponse-objects

https://docs.djangoproject.com/en/3.1/ref/request-response/#fileresponse-objects

Forms in Django

https://docs.djangoproject.com/en/3.1/topics/forms/

django.contrib.auth.authenticate

https://docs.djangoproject.com/en/3.1/topics/auth/default/#authenticating-users

使用django默认的或自定义的后台鉴权方法来对用户鉴权;自定义后端鉴权:

https://docs.djangoproject.com/en/3.1/topics/auth/customizing/#authentication-backends