Rest-framework-API参考-GenericAPIView

API Reference

GenericAPIView

This class extends REST framework's APIView class, adding commonly required behavior for standard list and detail views.

这个类扩展REST框架的apiview类,添加通常所要求的行为标准的列表视图和详细视图。

Each of the concrete generic views provided is built by combining GenericAPIView, with one or more mixin classes.

每个具体的通用视图提供genericapiview建相结合,与一个或多个混合类。

Attributes

属性

Basic settings:

基本设置:

The following attributes control the basic view behavior.

下列属性控制基本视图行为。

queryset - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the get_queryset() method. If you are overriding a view method, it is important that you call get_queryset() instead of accessing this property directly, as queryset will get evaluated once, and those results will be cached for all subsequent requests.

queryset-这个queryset属性用于从该视图的查询返回的对象。通常情况下,你必须设置这个属性,或重写get_queryset()方法。如果你重写视图的方法,那你可以使用get_queryset()来替代直接访问该属性,因为查询会评估一次,这些结果将被缓存,为后续所有的请求提供结果。

serializer_class - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the get_serializer_class() method.

serializer_class -这个序列化类可用于验证和反序列化、序列化的输入,输出。通常情况下,你必须设置这个属性,或重写get_serializer_class()方法。

lookup_field - The model field that should be used to for performing object lookup of individual model instances. Defaults to 'pk'. Note that when using hyperlinked APIs you'll need to ensure that both the API views and the serializer classes set the lookup fields if you need to use a custom value.

lookup_field -这个模型被用于执行单个模型的实例对象查找。默认为' PK '。注意,当使用超链接的API,你需要确保API视图和序列化类设置查阅字段如果你需要使用一个自定义的值。

lookup_url_kwarg - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as lookup_field.

lookup_url_kwarg-这个URL关键字参数应用于对象查找。URL中应包括相应于该值的关键字参数。如果未设置默认为使用相同的值作为lookup_field。

Pagination:

分页:

The following attributes are used to control pagination when used with list views.

下面的属性是用来控制分页时使用列表视图。

pagination_class - The pagination class that should be used when paginating list results. Defaults to the same value as the DEFAULT_PAGINATION_CLASS setting, which is 'rest_framework.pagination.PageNumberPagination'. Setting pagination_class=None will disable pagination on this view.

pagination_class-这个分页类应使用分页时结果的列表。默认值为DEFAULT_PAGINATION_CLASS设置相同的值,这是'rest_framework.pagination.PageNumberPagination'”。设置pagination_class =None将禁用此视图分页。

Filtering:

过滤:

filter_backends - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the DEFAULT_FILTER_BACKENDS setting.

filter_backends -目录过滤器后端类应该用于过滤查询。默认值为default_filter_backends设置相同的值。

Methods

方法

Base methods:

基本方法

get_queryset(self)

Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by thequerysetattribute.

This method should always be used rather than accessingself.querysetdirectly, asself.querysetgets evaluated only once, and those results are cached for all subsequent requests.

May be overridden to provide dynamic behavior, such as returning a queryset, that is specific to the user making the request.

返回可用于列表视图的查询,并可作为详细视图查询的基础。默认返回的查询属性指定的查询。

这种方法应该是用而不是直接访问self.queryset,作为self.queryset只被计算一次,这些结果被缓存用于所有后续的请求。

可能被提供的动态行为,如返回一个查询,是具体到发出请求的用户。

For example:

defget_queryset(self):user=self.request.userreturnuser.accounts.all()

get_object(self)

Returns an object instance that should be used for detail views. Defaults to using thelookup_fieldparameter to filter the base queryset.

May be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg.

返回应用于详细视图的对象实例。默认使用lookup_field参数滤波器的基础上查询。

可以重写提供更复杂的行为,如基于多个URL kwarg对象查找。

For example:

defget_object(self):queryset=self.get_queryset()filter={}forfieldinself.multiple_lookup_fields:filter[field]=self.kwargs[field]obj=get_object_or_404(queryset,**filter)self.check_object_permissions(self.request,obj)returnobj

Note that if your API doesn't include any object level permissions, you may optionally exclude theself.check_object_permissions, and simply return the object from theget_object_or_404lookup.

注意,如果你的API不包含任何对象级权限,你可以排除self.check_object_permissions,并简单地返回对象从get_object_or_404查找。

filter_queryset(self, queryset)

Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.

给定一个查询,通过过滤后返回一个新的查询。

For example:

deffilter_queryset(self,queryset):filter_backends=(CategoryFilter,)if'geo_route'inself.request.query_params:filter_backends=(GeoRouteFilter,CategoryFilter)elif'geo_point'inself.request.query_params:filter_backends=(GeoPointFilter,CategoryFilter)forbackendinlist(filter_backends):queryset=backend().filter_queryset(self.request,queryset,view=self)returnqueryset

get_serializer_class(self)

Returns the class that should be used for the serializer. Defaults to returning theserializer_classattribute.

May be overridden to provide dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users.

返回用于序列化的类。默认返回serializer_class属性。

可以重写提供动态的行为,如使用不同的序列化程序读取和写入操作,或提供不同的序列化程序的不同类型的用户。

For example:

defget_serializer_class(self):ifself.request.user.is_staff:returnFullAccountSerializerreturnBasicAccountSerializer

Save and deletion hooks:

保存或者删除钩子

The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.

通过混合类提供了以下方法,并提供了方便的对象保存或删除行为。

perform_create(self, serializer)- Called byCreateModelMixinwhen saving a new object instance. 当保存或者创建一个新的对象实例

perform_update(self, serializer)- Called byUpdateModelMixinwhen saving an existing object instance. 更改现有的对象实例

perform_destroy(self, instance)- Called byDestroyModelMixinwhen deleting an object instance. 删除对象实例

These hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.

这些钩子对于设置请求中隐含的属性特别有用,但不是请求数据的一部分。例如,可以根据请求用户或基于URL关键字参数设置对象的属性。

defperform_create(self,serializer):serializer.save(user=self.request.user)

These override points are also particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update.

这些附加点对于添加保存对象之前或之后发生的行为特别有用,如发送确认邮件或记录更新。

defperform_update(self,serializer):instance=serializer.save()send_email_confirmation(user=self.request.user,modified=instance)

You can also use these hooks to provide additional validation, by raising aValidationError(). This can be useful if you need some validation logic to apply at the point of database save. For example:

你也可以使用提供额外的验证这些挂钩,通过提高validationerror()。这可能是有用的,如果你需要一些验证逻辑应用在数据库保存点。例如:

defperform_create(self,serializer):queryset=SignupRequest.objects.filter(user=self.request.user)ifqueryset.exists():raiseValidationError('You have already signed up')serializer.save(user=self.request.user)

Note: These methods replace the old-style version 2.xpre_save,post_save,pre_deleteandpost_deletemethods, which are no longer available.

注意:这些方法取代旧版本2.x, 如pre_save,post_save,pre_delete和post_delete方法将不再可用。

Other methods:

其他方法:

You won't typically need to override the following methods, although you might need to call into them if you're writing custom views usingGenericAPIView.

你不需要重写以下方法,虽然你可能需要打电话到他们如果你使用GenericAPIView写自定义的视图。

get_serializer_context(self)- Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including'request','view'and'format'keys.

返回一个字典包含任何额外的上下文,应该提供给串行器。默认包括“request”,“view”和“format”键。

get_serializer(self, instance=None, data=None, many=False, partial=False)- Returns a serializer instance.返回一个序列化实例。

get_paginated_response(self, data)- Returns a paginated styleResponseobject.返回分页式的响应对象。

paginate_queryset(self, queryset)- Paginate a queryset if required, either returning a page object, orNoneif pagination is not configured for this view.

Paginate是一个查询集,如果需要的话,可以返回一个页面对象,或者如果没有分页则不需要配置。

filter_queryset(self, queryset)- Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.

给定一个查询,过滤后返回一个新的查询。

Mixins

The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as.get()and.post(), directly. This allows for more flexible composition of behavior.

mixin类提供用于提供基本观点的行为。注意mixin类提供方法而不是定义的处理方法等。get()和post()、直接。这允许更灵活的行为组合。

The mixin classes can be imported fromrest_framework.mixins.

mixin类可以从rest_framework.mixins引入。

ListModelMixin

Provides a.list(request, *args, **kwargs)method, that implements listing a queryset.

If the queryset is populated, this returns a200 OKresponse, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.

提供一个清单.list(request, *args, **kwargs)方法,实现上市的查询。

如果查询是稠密的,这会返回一个200 OK响应,一系列表示的查询响应的身体。响应数据可分页。

CreateModelMixin

Provides a.create(request, *args, **kwargs)method, that implements creating and saving a new model instance.

If an object is created this returns a201 Createdresponse, with a serialized representation of the object as the body of the response. If the representation contains a key namedurl, then theLocationheader of the response will be populated with that value.

If the request data provided for creating the object was invalid, a400 Bad Requestresponse will be returned, with the error details as the body of the response.

提供一个创建.create(request, *args, **kwargs)方法,实现创建并保存一个新的模型实例。

如果创建了对象,则返回一个201创建的响应,该对象的序列化表示形式作为响应的主体。如果表示包含一个名为URL的键,则响应的位置标头将填充该值。

如果为创建对象提供的请求数据无效,则返回400个错误请求响应,将错误详细信息作为响应的主体。

RetrieveModelMixin

Provides a.retrieve(request, *args, **kwargs)method, that implements returning an existing model instance in a response.

提供一个.retrieve(request, *args, **kwargs)方法,实现在响应返回一个现有的模型实例。

If an object can be retrieved this returns a200 OKresponse, with a serialized representation of the object as the body of the response. Otherwise it will return a404 Not Found.

如果可以检索对象,则返回一个200 OK响应,该对象的序列化表示形式作为响应的主体。否则会返回404没有找到。

UpdateModelMixin

Provides a.update(request, *args, **kwargs)method, that implements updating and saving an existing model instance.

Also provides a.partial_update(request, *args, **kwargs)method, which is similar to theupdatemethod, except that all fields for the update will be optional. This allows support for HTTPPATCHrequests.

If an object is updated this returns a200 OKresponse, with a serialized representation of the object as the body of the response.

If the request data provided for updating the object was invalid, a400 Bad Requestresponse will be returned, with the error details as the body of the response.

提供了一个.update(request, *args, **kwargs)方法,实现更新和保存现有的模型实例。

还提供了一个.partial_update(request, *args, **kwargs)方法,这是类似于更新的方法,除了对更新的所有字段都是可选的。这允许HTTP补丁请求的支持。

如果对象更新,则返回一个200 OK响应,该对象的序列化表示为响应的主体。

如果为更新对象提供的请求数据无效,则返回400错误请求响应,将错误详细信息作为响应的主体。

DestroyModelMixin

Provides a.destroy(request, *args, **kwargs)method, that implements deletion of an existing model instance.

If an object is deleted this returns a204 No Contentresponse, otherwise it will return a404 Not Found.

提供了一种.destroy(request, *args, **kwargs)方法,实现对现有模型实例的删除。

如果一个对象被删除,返回204没有内容的响应,否则它将返回一个没有找到的404错误。

Concrete View Classes

具体的视图类

The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior.

The view classes can be imported fromrest_framework.generics.

下面的类是具体的泛型视图。如果您使用的是通用视图,这一般都能使用到。除非您需要大量定制的行为。

这些视图类是从rest_framework.generics引入的

CreateAPIView

Used forcreate-onlyendpoints.

Provides apostmethod handler.

Extends:GenericAPIView,CreateModelMixin

ListAPIView

Used forread-onlyendpoints to represent acollection of model instances.

Provides agetmethod handler.

Extends:GenericAPIView,ListModelMixin

RetrieveAPIView

Used forread-onlyendpoints to represent asingle model instance.

Provides agetmethod handler.

Extends:GenericAPIView,RetrieveModelMixin

DestroyAPIView

Used fordelete-onlyendpoints for asingle model instance.

Provides adeletemethod handler.

Extends:GenericAPIView,DestroyModelMixin

UpdateAPIView

Used forupdate-onlyendpoints for asingle model instance.

Providesputandpatchmethod handlers.

Extends:GenericAPIView,UpdateModelMixin

ListCreateAPIView

Used forread-writeendpoints to represent acollection of model instances.

Providesgetandpostmethod handlers.

Extends:GenericAPIView,ListModelMixin,CreateModelMixin

RetrieveUpdateAPIView

Used forread or updateendpoints to represent asingle model instance.

Providesget,putandpatchmethod handlers.

Extends:GenericAPIView,RetrieveModelMixin,UpdateModelMixin

RetrieveDestroyAPIView

Used forread or deleteendpoints to represent asingle model instance.

Providesgetanddeletemethod handlers.

Extends:GenericAPIView,RetrieveModelMixin,DestroyModelMixin

RetrieveUpdateDestroyAPIView

Used forread-write-deleteendpoints to represent asingle model instance.

Providesget,put,patchanddeletemethod handlers.

Extends:GenericAPIView,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin

Customizing the generic views

Often you'll want to use the existing generic views, but use some slightly customized behavior. If you find yourself reusing some bit of customized behavior in multiple places, you might want to refactor the behavior into a common class that you can then just apply to any view or viewset as needed.

Creating custom mixins

For example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following:

classMultipleFieldLookupMixin(object):"""

Apply this mixin to any view or viewset to get multiple field filtering

based on a `lookup_fields` attribute, instead of the default single field filtering.

"""defget_object(self):queryset=self.get_queryset()# Get the base querysetqueryset=self.filter_queryset(queryset)# Apply any filter backendsfilter={}forfieldinself.lookup_fields:ifself.kwargs[field]:# Ignore empty fields.filter[field]=self.kwargs[field]returnget_object_or_404(queryset,**filter)# Lookup the object

You can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior.

classRetrieveUserView(MultipleFieldLookupMixin,generics.RetrieveAPIView):queryset=User.objects.all()serializer_class=UserSerializerlookup_fields=('account','username')

Using custom mixins is a good option if you have custom behavior that needs to be used.

Creating custom base classes

If you are using a mixin across multiple views, you can take this a step further and create your own set of base views that can then be used throughout your project. For example:

classBaseRetrieveView(MultipleFieldLookupMixin,generics.RetrieveAPIView):passclassBaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,generics.RetrieveUpdateDestroyAPIView):pass

Using custom base classes is a good option if you have custom behavior that consistently needs to be repeated across a large number of views throughout your project.

PUT as create

Prior to version 3.0 the REST framework mixins treatedPUTas either an update or a create operation, depending on if the object already existed or not.

AllowingPUTas create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning404responses.

Both styles "PUTas 404" and "PUTas create" can be valid in different circumstances, but from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious.

If you need to generic PUT-as-create behavior you may want to include something likethisAllowPUTAsCreateMixinclassas a mixin to your views.

Third party packages

The following third party packages provide additional generic view implementations.

Django REST Framework bulk

Thedjango-rest-framework-bulk packageimplements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.

Django Rest Multiple Models

Django Rest Multiple Modelsprovides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,013评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,205评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,370评论 0 342
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,168评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,153评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,954评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,271评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,916评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,382评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,877评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,989评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,624评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,209评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,199评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,418评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,401评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,700评论 2 345

推荐阅读更多精彩内容