API Guide (iv) generic views

Source: Internet
Author: User

Common view

Django ' s generic views ... were developed as a shortcut for common usage patterns ... They take some common idioms and patterns that are created and abstracted in view development so that you can quickly write a common view of your data without having to repeat it.

-Django Documentation

One of the main advantages of CBV is that the they allow you to compose bits of reusable behavior. REST Framework takes advantage of providing a number of pre-built views the provide for commonly used patterns.

The common view provided by the rest framework allows you to quickly build an API view that closely corresponds to a database model.

If the generic view does not meet your API requirements, you can pull down to use APIView the general class, or reuse the Mixins and base classes used by the common view to build a set of your own reusable generic views.

Example

Typically, when you use a common view, you will overwrite the view and set several class properties.

From django.contrib.auth.models import userfrom myapp.serializers import userserializerfrom rest_framework Import Genericsfrom rest_framework.permissions Import Isadminuserclass userlist (generics. Listcreateapiview):    queryset = User.objects.all ()    serializer_class = Userserializer    permission_classes = (Isadminuser,)

For more complex scenarios, you may also want to override the various methods on the view class. For example.

Class UserList (generics. Listcreateapiview):    queryset = User.objects.all ()    serializer_class = Userserializer    permission_classes = (Isadminuser,)    def list (self, request):        # Note The use of ' get_queryset () ' Instead of ' self.queryset '        query Set = Self.get_queryset ()        serializer = Userserializer (Queryset, many=true)        return Response (serializer.data)

For very simple cases, you might want to use this .as_view() method to pass any class property. For example, your urlconf may contain the following entries:

URL (r ' ^/users/', Listcreateapiview.as_view (Queryset=user.objects.all (), Serializer_class=userserializer), Name= ' User-list ')
API Reference Genericapiview

This class extends the rest framework's APIView classes, adding common behavior to standard lists and detailed views.

Each of the specific common views provided is built by GenericAPIView combining one or more mixin classes.

Property

Basic Settings :

The following properties control the basic view behavior.

    • queryset   -the query used to return objects from this view. Typically, you must set this property, or override get_queryset () method. If you override a view method, it is important to call Get_queryset () instead of directly accessing this property, as  queryset  will get evaluated Once, and those results'll be cached for all subsequent requests.
    • serializer_class   -Used to validate and deserialize the input and serialize the output. Typically, you must set this property, or override get_serializer_class () method.
    • Lookup_field   -the Model field used to perform object lookups for individual model instances. The default is ' PK ' . Note that when using a hyperlink API, if you need to use a custom value, you need to make sure that the API views  the and  the serializer classes all set the lookup field.
    • lookup_url_kwarg   -the URL keyword parameter that should be used for object lookups. The URL conf should contain the keyword parameter corresponding to the value. If you cancel the setting, the default is to use the same value as   Lookup_field .

Paging :

The following properties are used to control paging when using the list view.

    • pagination_class-The default DEFAULT_PAGINATION_CLASS is the same value as the ‘rest_framework.pagination.PageNumberPagination‘ setting, that is. Settings pagination_class=None will disable paging on this view.

Filter :

    • filter_backends-The default value DEFAULT_FILTER_BACKENDS is the same as the setting.
Method

Basic Methods :

get_queryset(self)

Returns the query set used for the list view and uses it as the basis for finding in the detailed view. The queryset specified queryset by the property is returned by default.

This method should always be used instead of direct access self.queryset , because self.queryset These results are cached for all subsequent requests every time that it is executed.

may be overwritten to provide dynamic behavior, such as returning a queryset, that's specific to the user making the request.

For example:

def get_queryset (self):    user = Self.request.user    return User.accounts.all ()
get_object(self)

Returns an instance of an object applied to a detailed view. The default parameter is used to lookup_field filter the base queryset.

may be overwritten to provide more complex behavior, such as object lookups based on multiple URL kwarg.

For example:

def get_object (self):    Queryset = Self.get_queryset ()    filter = {} for    field in Self.multiple_lookup_fields :        Filter[field] = Self.kwargs[field]    obj = get_object_or_404 (Queryset, **filter)    self.check_object_ Permissions (self.request, obj)    return obj

Note that if your API does not include any object-level permissions, you can selectively exclude self.check_object_permissions and return objects only from get_object_or_404 lookups.

filter_queryset(self, queryset)

Given a queryset, filter with any filter backends to return a new queryset.

For example:

def filter_queryset (self, queryset):    filter_backends = (categoryfilter,)    if ' Geo_route ' in Self.request.query _params:        filter_backends = (georoutefilter, categoryfilter)    elif ' Geo_point ' in Self.request.query_params:        filter_backends = (geopointfilter, categoryfilter) for    backend in list (filter_backends):        queryset = Backend (). Filter_queryset (Self.request, Queryset, view=self)    return Queryset
get_serializer_class(self)

Returns the class used for serialization. The default serializer_class return property.

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

For example:

def get_serializer_class (self):    if Self.request.user.is_staff:        return Fullaccountserializer    return Basicaccountserializer

Save and delete hooks:

The following methods are provided by the Mixin class and provide an easy way to override object save or delete behavior.

    • perform_create(self, serializer)- CreateModelMixin called when a new object instance is saved.
    • perform_update(self, serializer)- UpdateModelMixin called when an existing object instance is saved.
    • perform_destroy(self, instance)- DestroyModelMixin called when an object instance is deleted.

These hooks are especially useful for setting properties that are implied in a request, but are not part of the request data. For example, you can set properties on an object based on either the requesting user or the URL keyword parameter.

def perform_create(self, serializer): serializer.save(user=self.request.user)

These overlays are also particularly useful for adding behaviors that occur before or after the object is saved, such as sending acknowledgments or record updates.

def perform_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 ValidationError() . This is useful if you need to apply some validation logic when the database is saved. For example:

DefPerform_create(Self,Serializer):Queryset= Signuprequest.Objects.Filter (user=self. Request. User  if Queryset.< Span class= "PLN" >exists ():  raise validationerror ( "You had already signed up '  Serializer. (user=self.request.              

Note : These methods supersede the legacy version 2.x pre_save , post_save , pre_delete and post_delete methods, which will no longer be available.

Other methods :

Typically, you do not need to override the following methods, although you might need to call them if you use custom views to write custom views GenericAPIView .

    • get_serializer_context(self)-Returns a dictionary containing any additional contexts that should be provided to the serializer. The default is include ‘request‘ , ‘view‘ and ‘format‘ keys.
    • get_serializer(self, instance=None, data=None, many=False, partial=False)-Returns an instance of the serializer.
    • get_paginated_response(self, data)-Returns a paged style Response object.
    • paginate_queryset(self, queryset)-If necessary, the paging Finder returns the Page object, or None if no paging is configured for this view.
    • filter_queryset(self, queryset)-Given a query, use any filter back end to filter and return a new query.
Mixing

The Mixin class provides operations to provide basic view behavior. Note that the Mixin class provides an action method instead of defining a handler method, such as .get() and .post() , directly. This gives you more flexibility in combining behaviors.

The Mixin class can be imported from rest_framework.mixins .

Listmodelmixin

Provides a .list(request, *args, **kwargs) way to implement a list of query sets.

If the query is populated, a response is returned 200 OK , where serialization is represented as the principal of the query. The response data can optionally be paged.

Createmodelmixin

Provides a .create(request, *args, **kwargs) way to implement creating and saving new model instances.

If an object is created, a response is returned 201 Created , and the serialized representation of the object is used as the body of the response. If the representation contains a named key url , the Location header of the response is populated with that value.

If the requested data used to create the object is not valid, the response is returned with the 400 Bad Request error details as the body of the response.

Retrievemodelmixin

Provides a .retrieve(request, *args, **kwargs) way to implement returning an existing model instance in a response.

If the object can be retrieved, a 200 OK response is returned, where the serialization of the object is represented as the body of the response. Otherwise it will return 404 Not Found .

Updatemodelmixin

Provides a .update(request, *args, **kwargs) way to implement updating and saving an existing model instance.

A .partial_update(request, *args, **kwargs) method similar to this update method is also provided, but all updated fields will be optional. This allows HTTP requests to be supported PATCH .

If the object is updated, a response is returned 200 OK , and the serialized representation of the object is used as the body of the response.

If the requested data supplied for updating an object is not valid, the response is returned with the 400 Bad Request error details as the body of the response.

Destroymodelmixin

Provides a .destroy(request, *args, **kwargs) way to implement a delete of an existing model instance.

If the object is deleted, a response is returned 204 No Content , or one is returned 404 Not Found .

Concrete View Class

The following classes are specific general views. If you use a common view, this is usually the level you will be working on unless you need a lot of custom behavior.

View classes can be imported from rest_framework.generics .

Createapiview

Used to create only endpoints.

Provides a post method handler.

Extension: Genericapiview,createmodelmixin

Listapiview

Used for read-only endpoints to represent collections of model instances .

Provides a get method handler.

Extension: Genericapiview,listmodelmixin

Retrieveapiview

Used for read-only endpoints to represent a single model instance .

Provides a get method handler.

Extension: Genericapiview,retrievemodelmixin

Destroyapiview

A Delete-only endpoint for a single model instance .

Provides a delete method handler.

Extension: Genericapiview,destroymodelmixin

Updateapiview

the only update endpoint for a single model instance .

Provider put and patch method handlers.

Extension: Genericapiview,updatemodelmixin

Listcreateapiview

Used to read and write endpoints to represent collections of model instances .

Provider get and post method handlers.

Extension: Genericapiview,listmodelmixin,createmodelmixin

Retrieveupdateapiview

Used to read or update endpoints to represent a single model instance .

Provided get , put and the patch method is processed.

Extension: Genericapiview,retrievemodelmixin,updatemodelmixin

Retrievedestroyapiview

Used to read or delete endpoints to represent a single model instance .

Provider get and delete method handlers.

Extension: Genericapiview,retrievemodelmixin,destroymodelmixin

Retrieveupdatedestroyapiview

Used to read and write delete endpoints to represent a single model instance .

Provide get , put , patch and delete method to deal with.

Extension: Genericapiview,retrievemodelmixin,updatemodelmixin,destroymodelmixin

Customizing a common view

Typically, you will need to use the existing common view, but use some slightly customized behavior. If you find yourself reusing some custom behavior in multiple places, you might want to refactor the behavior into a generic class, and then apply it to any view or view as you want.

Creating a custom Mix

For example, if you need to find objects based on multiple fields in the URL conf, you can create a mixin class that looks like this:

Class Multiplefieldlookupmixin(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= {} ForFieldInch Self.Lookup_fields: If self.[field]: # Ignore empty fields.  Filter[field] = self.[field] return< Span class= "PLN" > Get_object_or_404 (queryset **filter)   # Lookup The object               

You can simply apply this mixin to a view or view as long as you need to apply the custom behavior.

 class retrieveuserview ( multiplefieldlookupmixin, Generics.< Span class= "Typ" >retrieveapiview):  Queryset =  user. Objects. All ()  Serializer_class =userserializer Lookup_fields = ( ' account ' ,  username '               /span>                

If you need to use custom behavior, it's a good choice to use a custom blend.

Create a custom base class

If you use mixin in multiple views, you can learn more about and create your own set of basic views that you can then use throughout your project. For example:

class BaseRetrieveView(MultipleFieldLookupMixin, generics.RetrieveAPIView): passclass BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin, generics.RetrieveUpdateDestroyAPIView): pass

Using a custom base class is a good choice, and if you have custom behavior, you always need to repeat in a large number of views throughout the project.

Put as the creation

Before version 3.0, the rest framework mixin is PUT considered an update or create operation, depending on whether the object already exists.

PUTbeing allowed as a creation is problematic because it inevitably exposes information about the existence or non-existence of an object. Transparently allowing re-creation of previously deleted instances is not a better default behavior, and not just a return response is not 404 obvious.

Two styles of " PUT 404" and " PUT create" can work in different situations, but from version 3.0 we now use 404 behavior as the default because it is simpler and more obvious.

If you need generic put, for creating behaviors, you may want to include AllowPUTAsCreateMixin your comments like this class.

Third-party Packages

The following third-party packages provide additional common view implementations.

Django REST Framework Batch

In Django's rest architecture, bulk implementations are mixed with generic views and some common concrete views allow bulk operations to be applied through API requests.

Django Rest Multiple models

The Django rest model provides a common view (and mixin) for sending multiple serialization models and/or queries through a single API request.

API Guide (iv) generic views

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.