1. Since the goods and goodscategory table in a model where it is logical classification of merchandise here is also written in goods.views.py
2. First write serializers.py
Import GoodsCategory .models from
# commodity class interface serialization # Let category field displays the total amount of goods of class CategorySerializer3 (serializers.ModelSerializer): class Meta: Model = GoodsCategory Fields = " __all__ " # Take all fields class CategorySerializer2 (serializers.ModelSerializer) : sub_cat = CategorySerializer3 (MANY = True) # MANY = True, i.e., the field has a plurality of values declared class Meta -: Model = GoodsCategory fields = " __all__ is " # Take all fields class CategorySerializer (serializers.ModelSerializer): sub_cat = CategorySerializer2 (MANY = True) # MANY = True, i.e., the field has a plurality of values declared class Meta -: Model = GoodsCategory Fields = " __all__ is " # Take all fields
3. Then write goods.views.py of CategorysViewSet
from .serializers Import CategorySerializer # Product Category Interface # demand: one nested inside the second-class, second-class nested inside three # RetrieveModelMixin function is to help us complete url configuration, / categorys / id, id you can get by typing to an element specified class CategoryViewSet (mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): "" " list: Categories list data " "" QuerySet = GoodsCategory.objects.filter (category_type = 1 ) serializer_class = CategorySerializer
4. Finally, to configure url, in principle, we need to provide artificial url to "get some details of a classified" function, but RetrieveModelMixin previously used has completely helped us encapsulate this functionality
Features detailed in the following figure
urls.py
from goods.views Import CategoryViewSet # Configure the category url, no separate configuration category / id's URL router.register (R & lt ' categorys ' , CategoryViewSet, the basename = " categorys " ) # Router will automatically get to the list, the post go to create a
5. Go to the browser to verify
First checks whether or not the nested loop, and then verify that a particular category can be individually removed, there is no problem as shown below
----- over --------