Django笔记1

来源:互联网 发布:vb编程界面 编辑:程序博客网 时间:2024/05/29 14:23

1、

url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),

The question_id=’34’ part comes from (?P[0-9]+). Using parentheses around a pattern “captures” the text matched by that pattern and sends it as an argument to the view function; ?P defines the name that will be used to identify the matched pattern; and [0-9]+ is a regular expression to match a sequence of digits (i.e., a number).
2、
Each view is responsible for doing one of two things: returning an HttpResponse object containing the content for the requested page, or raising an exception such as Http404. The rest is up to you.

Your view can read records from a database, or not. It can use a template system such as Django’s – or a third-party Python template system – or not. It can generate a PDF file, output XML, create a ZIP file on the fly, anything you want, using whatever Python libraries you want.

All Django wants is that HttpResponse. Or an exception.
3、
django models.pk是主键的意思。pk即primary key
4、
model字段查询关键字汇总,例如我们有一个model是Question,Question有一个字段是pub_date,我们可以使用如下代码:
Question.objects.filter(pub_date__lte=timezone.now())
来寻找pub_date小于等于timezone.now()的Question。其中__lte表达的就是小于等于的意思。以下是一些类似的查询关键字:
exact, 精确等于
iexact,精确等于但忽略大小写
contains,包含
icontains, 包含但忽略大小写
startswith, 以什么开头
istartswith, 以什么开头但忽略大小写
endswith, 以什么结尾
iendswith,以什么结尾但忽略大小写
lt,即less than
gt,即great than
lte,即less than or equal
gte,即great than or equal
in,即存在于一个list范围内
__range 在…范围内
__year 日期字段的年份
__month 日期字段的月份
__day 日期字段的日
__isnull=True/False
5、关于reverse
from django.urls import reverse
Django中提供了一个关于URL的映射的解决方案,你可以做两个方向的使用:
1.有客户端的浏览器发起一个url请求,Django根据URL解析,把url中的参数捕获,调用相应的试图,获取相应的数据,然后返回给客户端显示
2.通过一个视图的名字,再加上一些参数和值,逆向获取相应的URL

reverse(loopup_view,args,kwargs)

loopup_view是要执行动作的路径,args是固定参数,kwargs是动态参数

举例:url=reverse(‘polls:detail’,args=(future_question.id,))
polls是app_name,detail是url pattern的name,args向其中传参,是一个tuple
6、

原创粉丝点击