|
|
@ -1,5 +1,5 @@
|
|
|
|
source: mixins.py
|
|
|
|
source: mixins.py
|
|
|
|
generics.py
|
|
|
|
generics.py
|
|
|
|
|
|
|
|
|
|
|
|
# Generic views
|
|
|
|
# Generic views
|
|
|
|
|
|
|
|
|
|
|
@ -7,7 +7,7 @@ source: mixins.py
|
|
|
|
>
|
|
|
|
>
|
|
|
|
> — [Django Documentation][cite]
|
|
|
|
> — [Django Documentation][cite]
|
|
|
|
|
|
|
|
|
|
|
|
One of the key benefits of class-based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.
|
|
|
|
One of the key benefits of class-based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.
|
|
|
|
|
|
|
|
|
|
|
|
The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.
|
|
|
|
The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.
|
|
|
|
|
|
|
|
|
|
|
@ -27,7 +27,7 @@ Typically when using the generic views, you'll override the view, and set severa
|
|
|
|
serializer_class = UserSerializer
|
|
|
|
serializer_class = UserSerializer
|
|
|
|
permission_classes = (IsAdminUser,)
|
|
|
|
permission_classes = (IsAdminUser,)
|
|
|
|
|
|
|
|
|
|
|
|
For more complex cases you might also want to override various methods on the view class. For example.
|
|
|
|
For more complex cases you might also want to override various methods on the view class. For example.
|
|
|
|
|
|
|
|
|
|
|
|
class UserList(generics.ListCreateAPIView):
|
|
|
|
class UserList(generics.ListCreateAPIView):
|
|
|
|
queryset = User.objects.all()
|
|
|
|
queryset = User.objects.all()
|
|
|
@ -40,9 +40,9 @@ For more complex cases you might also want to override various methods on the vi
|
|
|
|
serializer = UserSerializer(queryset, many=True)
|
|
|
|
serializer = UserSerializer(queryset, many=True)
|
|
|
|
return Response(serializer.data)
|
|
|
|
return Response(serializer.data)
|
|
|
|
|
|
|
|
|
|
|
|
For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something like the following entry:
|
|
|
|
For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something like the following entry:
|
|
|
|
|
|
|
|
|
|
|
|
re_path(r'^/users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')
|
|
|
|
path('users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')
|
|
|
|
|
|
|
|
|
|
|
|
---
|
|
|
|
---
|
|
|
|
|
|
|
|
|
|
|
@ -60,20 +60,20 @@ Each of the concrete generic views provided is built by combining `GenericAPIVie
|
|
|
|
|
|
|
|
|
|
|
|
The following attributes control the basic view behavior.
|
|
|
|
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` - 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.
|
|
|
|
* `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` - 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.
|
|
|
|
* `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` - 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_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` - 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`.
|
|
|
|
|
|
|
|
|
|
|
|
**Pagination**:
|
|
|
|
**Pagination**:
|
|
|
|
|
|
|
|
|
|
|
|
The following attributes are used to control pagination when used with list views.
|
|
|
|
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` - 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.
|
|
|
|
|
|
|
|
|
|
|
|
**Filtering**:
|
|
|
|
**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` - 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.
|
|
|
|
|
|
|
|
|
|
|
|
### Methods
|
|
|
|
### Methods
|
|
|
|
|
|
|
|
|
|
|
@ -81,7 +81,7 @@ The following attributes are used to control pagination when used with list view
|
|
|
|
|
|
|
|
|
|
|
|
#### `get_queryset(self)`
|
|
|
|
#### `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 the `queryset` attribute.
|
|
|
|
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 the `queryset` attribute.
|
|
|
|
|
|
|
|
|
|
|
|
This method should always be used rather than accessing `self.queryset` directly, as `self.queryset` gets evaluated only once, and those results are cached for all subsequent requests.
|
|
|
|
This method should always be used rather than accessing `self.queryset` directly, as `self.queryset` gets evaluated only once, and those results are cached for all subsequent requests.
|
|
|
|
|
|
|
|
|
|
|
@ -95,7 +95,7 @@ For example:
|
|
|
|
|
|
|
|
|
|
|
|
#### `get_object(self)`
|
|
|
|
#### `get_object(self)`
|
|
|
|
|
|
|
|
|
|
|
|
Returns an object instance that should be used for detail views. Defaults to using the `lookup_field` parameter to filter the base queryset.
|
|
|
|
Returns an object instance that should be used for detail views. Defaults to using the `lookup_field` parameter to filter the base queryset.
|
|
|
|
|
|
|
|
|
|
|
|
May be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg.
|
|
|
|
May be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg.
|
|
|
|
|
|
|
|
|
|
|
@ -134,7 +134,7 @@ For example:
|
|
|
|
|
|
|
|
|
|
|
|
#### `get_serializer_class(self)`
|
|
|
|
#### `get_serializer_class(self)`
|
|
|
|
|
|
|
|
|
|
|
|
Returns the class that should be used for the serializer. Defaults to returning the `serializer_class` attribute.
|
|
|
|
Returns the class that should be used for the serializer. Defaults to returning the `serializer_class` attribute.
|
|
|
|
|
|
|
|
|
|
|
|
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.
|
|
|
|
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.
|
|
|
|
|
|
|
|
|
|
|
@ -149,11 +149,11 @@ For example:
|
|
|
|
|
|
|
|
|
|
|
|
The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.
|
|
|
|
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 by `CreateModelMixin` when saving a new object instance.
|
|
|
|
- `perform_create(self, serializer)` - Called by `CreateModelMixin` when saving a new object instance.
|
|
|
|
* `perform_update(self, serializer)` - Called by `UpdateModelMixin` when saving an existing object instance.
|
|
|
|
- `perform_update(self, serializer)` - Called by `UpdateModelMixin` when saving an existing object instance.
|
|
|
|
* `perform_destroy(self, instance)` - Called by `DestroyModelMixin` when deleting an object instance.
|
|
|
|
- `perform_destroy(self, instance)` - Called by `DestroyModelMixin` when 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.
|
|
|
|
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.
|
|
|
|
|
|
|
|
|
|
|
|
def perform_create(self, serializer):
|
|
|
|
def perform_create(self, serializer):
|
|
|
|
serializer.save(user=self.request.user)
|
|
|
|
serializer.save(user=self.request.user)
|
|
|
@ -178,17 +178,17 @@ You can also use these hooks to provide additional validation, by raising a `Val
|
|
|
|
|
|
|
|
|
|
|
|
You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using `GenericAPIView`.
|
|
|
|
You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using `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.
|
|
|
|
- `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.
|
|
|
|
* `get_serializer(self, instance=None, data=None, many=False, partial=False)` - Returns a serializer instance.
|
|
|
|
- `get_serializer(self, instance=None, data=None, many=False, partial=False)` - Returns a serializer instance.
|
|
|
|
* `get_paginated_response(self, data)` - Returns a paginated style `Response` object.
|
|
|
|
- `get_paginated_response(self, data)` - Returns a paginated style `Response` object.
|
|
|
|
* `paginate_queryset(self, queryset)` - Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view.
|
|
|
|
- `paginate_queryset(self, queryset)` - Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view.
|
|
|
|
* `filter_queryset(self, queryset)` - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
|
|
|
|
- `filter_queryset(self, queryset)` - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
|
|
|
|
|
|
|
|
|
|
|
|
---
|
|
|
|
---
|
|
|
|
|
|
|
|
|
|
|
|
# Mixins
|
|
|
|
# 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.
|
|
|
|
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.
|
|
|
|
|
|
|
|
|
|
|
|
The mixin classes can be imported from `rest_framework.mixins`.
|
|
|
|
The mixin classes can be imported from `rest_framework.mixins`.
|
|
|
|
|
|
|
|
|
|
|
@ -196,13 +196,13 @@ The mixin classes can be imported from `rest_framework.mixins`.
|
|
|
|
|
|
|
|
|
|
|
|
Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset.
|
|
|
|
Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset.
|
|
|
|
|
|
|
|
|
|
|
|
If the queryset is populated, this returns a `200 OK` response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.
|
|
|
|
If the queryset is populated, this returns a `200 OK` response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.
|
|
|
|
|
|
|
|
|
|
|
|
## CreateModelMixin
|
|
|
|
## CreateModelMixin
|
|
|
|
|
|
|
|
|
|
|
|
Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance.
|
|
|
|
Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance.
|
|
|
|
|
|
|
|
|
|
|
|
If an object is created this returns a `201 Created` response, with a serialized representation of the object as the body of the response. If the representation contains a key named `url`, then the `Location` header of the response will be populated with that value.
|
|
|
|
If an object is created this returns a `201 Created` response, with a serialized representation of the object as the body of the response. If the representation contains a key named `url`, then the `Location` header of the response will be populated with that value.
|
|
|
|
|
|
|
|
|
|
|
|
If the request data provided for creating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response.
|
|
|
|
If the request data provided for creating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response.
|
|
|
|
|
|
|
|
|
|
|
@ -210,13 +210,13 @@ If the request data provided for creating the object was invalid, a `400 Bad Req
|
|
|
|
|
|
|
|
|
|
|
|
Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response.
|
|
|
|
Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response.
|
|
|
|
|
|
|
|
|
|
|
|
If an object can be retrieved this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise it will return a `404 Not Found`.
|
|
|
|
If an object can be retrieved this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise it will return a `404 Not Found`.
|
|
|
|
|
|
|
|
|
|
|
|
## UpdateModelMixin
|
|
|
|
## UpdateModelMixin
|
|
|
|
|
|
|
|
|
|
|
|
Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance.
|
|
|
|
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 the `update` method, except that all fields for the update will be optional. This allows support for HTTP `PATCH` requests.
|
|
|
|
Also provides a `.partial_update(request, *args, **kwargs)` method, which is similar to the `update` method, except that all fields for the update will be optional. This allows support for HTTP `PATCH` requests.
|
|
|
|
|
|
|
|
|
|
|
|
If an object is updated this returns a `200 OK` response, with a serialized representation of the object as the body of the response.
|
|
|
|
If an object is updated this returns a `200 OK` response, with a serialized representation of the object as the body of the response.
|
|
|
|
|
|
|
|
|
|
|
@ -232,7 +232,7 @@ If an object is deleted this returns a `204 No Content` response, otherwise it w
|
|
|
|
|
|
|
|
|
|
|
|
# Concrete View Classes
|
|
|
|
# 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 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 from `rest_framework.generics`.
|
|
|
|
The view classes can be imported from `rest_framework.generics`.
|
|
|
|
|
|
|
|
|
|
|
@ -312,7 +312,7 @@ Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyMod
|
|
|
|
|
|
|
|
|
|
|
|
# Customizing the generic views
|
|
|
|
# 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.
|
|
|
|
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
|
|
|
|
## Creating custom mixins
|
|
|
|
|
|
|
|
|
|
|
@ -345,7 +345,7 @@ Using custom mixins is a good option if you have custom behavior that needs to b
|
|
|
|
|
|
|
|
|
|
|
|
## Creating custom base classes
|
|
|
|
## 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:
|
|
|
|
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:
|
|
|
|
|
|
|
|
|
|
|
|
class BaseRetrieveView(MultipleFieldLookupMixin,
|
|
|
|
class BaseRetrieveView(MultipleFieldLookupMixin,
|
|
|
|
generics.RetrieveAPIView):
|
|
|
|
generics.RetrieveAPIView):
|
|
|
@ -383,13 +383,12 @@ The [django-rest-framework-bulk package][django-rest-framework-bulk] implements
|
|
|
|
|
|
|
|
|
|
|
|
[Django Rest Multiple Models][django-rest-multiple-models] provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.
|
|
|
|
[Django Rest Multiple Models][django-rest-multiple-models] provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
[cite]: https://docs.djangoproject.com/en/stable/ref/class-based-views/#base-vs-generic-views
|
|
|
|
[cite]: https://docs.djangoproject.com/en/stable/ref/class-based-views/#base-vs-generic-views
|
|
|
|
[GenericAPIView]: #genericapiview
|
|
|
|
[genericapiview]: #genericapiview
|
|
|
|
[ListModelMixin]: #listmodelmixin
|
|
|
|
[listmodelmixin]: #listmodelmixin
|
|
|
|
[CreateModelMixin]: #createmodelmixin
|
|
|
|
[createmodelmixin]: #createmodelmixin
|
|
|
|
[RetrieveModelMixin]: #retrievemodelmixin
|
|
|
|
[retrievemodelmixin]: #retrievemodelmixin
|
|
|
|
[UpdateModelMixin]: #updatemodelmixin
|
|
|
|
[updatemodelmixin]: #updatemodelmixin
|
|
|
|
[DestroyModelMixin]: #destroymodelmixin
|
|
|
|
[destroymodelmixin]: #destroymodelmixin
|
|
|
|
[django-rest-framework-bulk]: https://github.com/miki725/django-rest-framework-bulk
|
|
|
|
[django-rest-framework-bulk]: https://github.com/miki725/django-rest-framework-bulk
|
|
|
|
[django-rest-multiple-models]: https://github.com/MattBroach/DjangoRestMultipleModels
|
|
|
|
[django-rest-multiple-models]: https://github.com/MattBroach/DjangoRestMultipleModels
|
|
|
|