Django 05Django-DRF (ModelViewSet), routing components, custom functions

1. Django-DRF (ModelViewSet)

1.1 What is DRF?

ModelViewSet is a viewset class provided by Django REST framework, which encapsulates common model operation methods.

The model class provides the default addition, deletion, modification and query functions.

It inherits from GenericViewSet, ListModelMixin, RetrieveModelMixin, CreateModelMixin, UpdateModelMixin, DestoryModelMixin.

Knowledge points Request url Features
GenericViewSet Provides a set of common view methods to facilitate the implementation of specific functions
ListModelMixin get 127.0.0.1:8000/book/ Provides the list method, use Get the resource list at
RetrieveModelMixin get 127.0.0.1:8000/book/{ 1}/ Provide the retrieve method for getting detailed information of a single resource
CreateModelMixin post 127.0.0.1:8000/book/ Provides the create method for creating resources< /strong>
UpdateModelMixin put 127.0.0.1:8000/book/{1}/ Provides the update method for updating resources
DestroyModelMixin detete 127.0.0.1:8000/book/{1}/ Provides the destroy method for deleting resources
Custom get/post 127.0.0.1:8000/book/custom User-defined method/ Function

These technical knowledge points can be used together to help us quickly build web applications with CRUD functions, and follow the conventions and best practices of the Django framework. Their application scenarios include various types of web applications such as blog systems, e-commerce platforms, and social networks. By using these technical knowledge points, we can improve development efficiency, reduce repetitive code writing work, and ensure code consistency and maintainability.

1.2 How to use

Set the queryset attribute to the collection of objects to be queried, and set the serializer_class attribute to the corresponding serializer class.

1.2.1 Example

view.py

from rest_framework.viewsets import ModelViewSet
class YourModelViewSet(ModelViewSet):
    queryset = YourModel.objects.all()
    serializer_class = YourModelSerializer

After using ModelViewSet, you will automatically get the default CRUD methods.

from rest_framework.decorators import action
#### modelviewset
class GoodsCategoryViewSet(ModelViewSet):
    #Specify query set (data used)
    queryset = GoodsCategory.objects.all()
    #Specify the serialization container used by the query set
    serializer_class = GoodsCategorySerializer

    @action(detail=False, methods=['get'])
    def latest(self, request):
        latest_obj = GoodsCategory.objects.latest('id')
        print(latest_obj)
        return Response("hello you called a custom function")

serializer.py

class GoodsSerializer(ModelSerializer):

    # Data related to foreign key fields needs to be written separately
    category = GoodsCategorySerializer()

    class Meta:
        #Specify the table to be serialized
        model = Goods
        #Specify the fields we need to serialize
        fields = '__all__'

2. Django-DRF routing component

2.1 What is the routing component?

DefaultRouter is a router class provided in Django REST framework, which is used to automatically generate URL routes.

A router is a mechanism that associates URLs with view functions or viewsets. Django REST framework’s router can automatically generate standard URL routes through simple configuration, thereby reducing the workload of manually writing URL routes.

2.2 How to use DefaultRouter

urls.py

from django.contrib import admin
from django.urls import path
from apps.erp_test.views import *

from rest_framework import routers

router = routers.DefaultRouter()
router.register('GoodsCategory', GoodsCategoryViewSet)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('filtergoodscategory/', FilterGoodsCategory),
    path('insertgoodscategory/', InsertGoodsCategory),
    path('filtergoodscategoryapi/', FilterGoodsCategoryAPI.as_view()),
    path('getgoods/', GetGoods.as_view()),
]


urlpatterns + = router.urls


The main thing is to add all the methods in a class to the routing.

Use routers.DefaultRouter()? to create a default router object, and use the router.register()? method to register a view set, GoodsCategoryViewSet code>?. This can automatically generate the corresponding URL route for this view set and add it to urlpatterns?.



3. Django-DRF custom function

3.1 What is a custom function

from rest_framework.decorators import action

@action is a decorator in the Django REST framework, used to convert a custom function into an action in the viewset. The @action decorator provides a way to define custom functions. These functions do not directly correspond to standard CRUD operations (Create-Read-Update-Delete), but implement some other custom functions. Define behavior or business logic.
The “@action decorator” is used to create custom actions in ViewSet, providing a more flexible application for ViewSet and @action only takes effect in the ViewSet view set. The additional action decorator in the view set can receive two parameters:
(1) methods: declare the request method corresponding to the action.
(2) detail: True/False declares whether the path of the action is the request method corresponding to the action.

3.2 How to use

views.py

class GoodsCategoryViewSet(ModelViewSet):
    #Specify query set (data used)
    queryset = GoodsCategory.objects.all()
    #Specify the serialization container used by the query set
    serializer_class = GoodsCategorySerializer

    @action(detail=False, methods=['get'])
    def latest(self, request):
        latest_obj = GoodsCategory.objects.latest('id')
        print(latest_obj)
        return Response("hello you called a custom function")


    @action(detail=False, methods=['get','post'])
    def delete_example(self, request):
        name = request.data.get('name')
        # Delete the product named 'name'
        categories_to_delete = GoodsCategory.objects.filter(name=name)
        # Use delete() method to delete objects
        deleted_count= categories_to_delete.delete()
        print(f"Deleted {<!-- -->deleted_count} categories.")

    @action(detail=False, methods=['get','post'])
    def create_example(self, request):
        name = request.data.get('name')
            # Use the create() method to create a new product classification object
        created_category = GoodsCategory.objects.create(name)
        print("Created category:", created_category)

Among them, detail=False means that the action does not need to process a single object, but the entire collection;

Functions decorated with @action need to be defined as methods in the viewset class, and when using router.register() to register the viewset, you need to specify basename parameter to ensure that the action’s URL maps correctly to the viewset.