简体   繁体   中英

Hierarchical Router Django Rest

So I have a Django project in which each app manages some type of a data table. Thus all of them follow a similar format in which there is a Table and Item model, each with an accompanying serializer and viewset. I'd like my apps to function such that there is no naming conflict between models of the same name in different apps. I would also like the router to act in a hierarchy first listing all the apps in the renderer in the form of /api/{app} and once you click it will give you the viewsets such as:

/api/{app}/table

/api/{app}/item

I've tried playing around with DefaultRouter and SimpleRouter but couldn't really managed to get anything to work properly.

I think what you need is a " Nested Router " which is available as a PyPi package (it's recommended in official DRF documentation in the Third Party Packages section).

In a shortcut you may use it in the following manner ( docs ):

/domain/ <- Domains list
/domain/{pk}/ <- One domain, from {pk}
/domain/{domain_pk}/nameservers/ <- Nameservers of domain from {domain_pk}
/domain/{domain_pk}/nameservers/{pk} <- Specific nameserver from {pk}, of domain from {domain_pk}

In your case code would look like:

from rest_framework_nested.routers import NestedSimpleRouter

router = DefaultRouter()
router.register(r'app', AppViewSet, basename='app')

app_router = NestedSimpleRouter(router, 'app', lookup='app')
app_router.register(r'table', TableViewSet, basename='table')
app_router.register(r'item', ItemViewSet, basename='item')

And then you must override get_queryset() method:

class TableViewSet(viewsets.ModelViewSet):
    def get_queryset(self):
        return Table.objects.filter(
            app=self.kwargs.get('app_pk'),
        )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM