内置基于类的视图 APILink to this heading
基于类的视图 API 参考。关于介绍性材料,请参见 基于类的视图 主题指南。
规范Link to this heading
基于类的视图所服务的每个请求都有一个独立的状态,因此,在实例上存储状态变量是安全的(即,self.foo = 3 是一个线程安全的操作)。
A class-based view is deployed into a URL pattern using the
as_view() classmethod:
urlpatterns = [
path("view/", MyView.as_view(size=42)),
]
Arguments passed into as_view() will
be assigned onto the instance that is used to service a request. Using the
previous example, this means that every request on MyView is able to use
self.size. Arguments must correspond to attributes that already exist on
the class (return True on a hasattr check).
基础 vs 通用视图Link to this heading
基于类的基本视图可被视为 父 类视图,可自行使用或继承。它们可能无法提供项目所需的所有功能,在这种情况下,有混入来扩展基本视图的功能。
Django 的通用视图是在这些基础视图的基础上建立起来的,是作为显示对象详情等常见使用模式的快捷方式而开发的。它们采用了视图开发中的某些常见的习惯和模式,并将其抽象化,这样你就可以快速编写数据的通用视图,而不必重复。
大多数通用视图需要使用 queryset 键,它是一个 QuerySet 实例;关于 QuerySet 对象的更多信息,请参见 执行查询。