Marking models to create REST APIs
Marking custom models¶
To create REST APIs for a model, first we need to mark the model. And to mark the model, use the decorator to_rest.decorators.restifyModel
. The decorator can be used in the following two ways:
-
Without Parameters: When used without parameters, all the defaults would be applied. For example:
- Import the decorator from the library
- Note the way decorator is used
- Note the way decorator is used
-
With Parameters: The decorator accepts the following parameters
customViewParams (str)
: This accepts the name of aViewParams
class. TheViewParams
class needs to override the class methodgetParams()
to provide customized methods and attributes for view set. For example, custom serializer, list method, create method, retreive method, update method, partial_update method, delete method, get_object method, get_queryset, etc. ThegetParams()
method must return a dictionary.excludeFields (list)
: The fields that needs to be excluded from the JSON object. Provided fields will not be included in the serializer. If customSerializer is provided then this parameter will be ignored.methodFields (list)
: The list of methods as read only fields. This can be used to include the model's methods' output as field. This includes only those field that don't take any parameter.
An example of passing custom serializer is given below:
- Here, test_basics is the directory of the app
- Here, test_basics is the directory of the app
In the above example, a custom serializer has been created in serializers.py
. A ViewParams
class, CustomSerializer
is created in view_params.py
to provide the custom serializer. And the name of the ViewParams
class is provided in decorator at line 4 in models.py
.
Note
All ViewParams
classes must be in the module view_params
in the directory of the app. That means, in the same location where models.py
is located. Django-to-rest will get the name of the ViewParams
class from the decorator and will search that class in the module view_params.
Hence, in the example above, CustomSerializer
is created in view_params.py
.
Marking models provided by Django¶
To create REST APIs for models provided by django, the models can be marked as follows: