{"id":13481722,"url":"https://github.com/alanjds/drf-nested-routers","last_synced_at":"2025-05-12T13:17:32.997Z","repository":{"id":10924381,"uuid":"13226530","full_name":"alanjds/drf-nested-routers","owner":"alanjds","description":"Nested Routers for Django Rest Framework","archived":false,"fork":false,"pushed_at":"2025-03-13T22:08:29.000Z","size":9298,"stargazers_count":1741,"open_issues_count":45,"forks_count":165,"subscribers_count":19,"default_branch":"master","last_synced_at":"2025-05-12T13:17:16.280Z","etag":null,"topics":["django","django-rest-framework","hacktoberfest","nested-resources","rest"],"latest_commit_sha":null,"homepage":"https://pypi.org/project/drf-nested-routers/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/alanjds.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2013-09-30T20:33:52.000Z","updated_at":"2025-05-12T12:46:28.000Z","dependencies_parsed_at":"2023-12-31T14:28:24.988Z","dependency_job_id":"e14f1870-1193-411b-9811-45ab34f95ba4","html_url":"https://github.com/alanjds/drf-nested-routers","commit_stats":{"total_commits":289,"total_committers":55,"mean_commits":5.254545454545455,"dds":0.5051903114186851,"last_synced_commit":"af270d718df88e6929e5dfbf4ad6a1e1955310b0"},"previous_names":[],"tags_count":72,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alanjds%2Fdrf-nested-routers","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alanjds%2Fdrf-nested-routers/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alanjds%2Fdrf-nested-routers/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alanjds%2Fdrf-nested-routers/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/alanjds","download_url":"https://codeload.github.com/alanjds/drf-nested-routers/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253745196,"owners_count":21957319,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["django","django-rest-framework","hacktoberfest","nested-resources","rest"],"created_at":"2024-07-31T17:00:54.739Z","updated_at":"2025-05-12T13:17:32.961Z","avatar_url":"https://github.com/alanjds.png","language":"Python","funding_links":[],"categories":["action_patterns","Packages"],"sub_categories":["build_full_docs","Routing"],"readme":"**This is a work in progress. It \"works for me\" at www.apiregistro.com.br,\nbut I cannot warranty that it fully \"works everywhere\" yet. Join us on Gitter (below) if you need some help.**\n\n# drf-nested-routers\n\n[![Join the chat at https://gitter.im/alanjds/drf-nested-routers](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/alanjds/drf-nested-routers?utm_source=badge\u0026utm_medium=badge\u0026utm_campaign=pr-badge\u0026utm_content=badge)\n[![Build Status](https://github.com/alanjds/drf-nested-routers/workflows/CI/badge.svg)](https://github.com/alanjds/drf-nested-routers/actions?query=workflow%3ACI+branch%3Amaster)\n\nThis package provides routers and fields to create nested resources in the [Django Rest Framework](http://django-rest-framework.org/)\n\nNested resources are needed for full REST URL structure, if one resource lives inside another.\n\nThe following example is about Domains and DNS Nameservers.\nThere are many domains, and each domain has many nameservers. The \"nameserver\" resource does not\nexist without a domain, so you need it \"nested\" inside the domain.\n\n\n## Requirements \u0026 Compatibility\n\n- Python (3.9, 3.10, 3.11, 3.12, 3.13)\n- Django (4.2, 5.0, 5.1)\n- Django REST Framework (3.14, 3.15)\n\nIt may work with lower versions, but since the release **0.94.2** is no more tested on CI for Python 3.8 or lower.\u003cbr/\u003e\nAnd since **0.92.1** is no more tested on CI for Pythons 2.7 to 3.5, Django 1.11 to 2.1 or DRF 3.6 to 3.10.\u003cbr/\u003e\nBefore that, the release **0.90.2** was tested also with DRF 2.4.3 up to 3.7.\n\n\n## Installation\n\nYou can install this library using pip:\n\n```pip install drf-nested-routers```\n\nIt is not needed to add this library in your Django project's `settings.py` file, as it does not contain any app, signal or model.\n\n## Quickstart\n\nThe desired URL signatures are:\n```\n/domains/ \u003c- Domains list\n/domains/{pk}/ \u003c- One domain, from {pk}\n/domains/{domain_pk}/nameservers/ \u003c- Nameservers of domain from {domain_pk}\n/domains/{domain_pk}/nameservers/{pk} \u003c- Specific nameserver from {pk}, of domain from {domain_pk}\n```\n\nHow to do it (example):\n```python\n# urls.py\nfrom rest_framework_nested import routers\nfrom views import DomainViewSet, NameserverViewSet\n(...)\n\nrouter = routers.SimpleRouter()\nrouter.register(r'domains', DomainViewSet)\n\ndomains_router = routers.NestedSimpleRouter(router, r'domains', lookup='domain')\ndomains_router.register(r'nameservers', NameserverViewSet, basename='domain-nameservers')\n# 'basename' is optional. Needed only if the same viewset is registered more than once\n# Official DRF docs on this option: http://www.django-rest-framework.org/api-guide/routers/\n\nurlpatterns = [\n    path(r'', include(router.urls)),\n    path(r'', include(domains_router.urls)),\n]\n```\n\n```python\n# views.py\n\n## For Django' ORM-based resources ##\n\nclass NameserverViewSet(viewsets.ModelViewSet):\n    def get_queryset(self):\n        return Nameserver.objects.filter(domain=self.kwargs['domain_pk'])\n\n## OR: non-ORM resources ##\n\nclass NameserverViewSet(viewsets.ViewSet):\n    def list(self, request, domain_pk=None):\n        nameservers = self.queryset.filter(domain=domain_pk)\n        (...)\n        return Response([...])\n\n    def retrieve(self, request, pk=None, domain_pk=None):\n        nameservers = self.queryset.get(pk=pk, domain=domain_pk)\n        (...)\n        return Response(serializer.data)\n```\n\n## Advanced\n\n### Hyperlinks for Nested resources\n\n**(optional)** If you need hyperlinks for nested relations, you need a custom serializer.\n\nThere you will inform how to access the *parent* of the instance being serialized when\nbuilding the *children* URL.\n\nIn the following example, an instance of Nameserver on `/domain/{domain_pk}/nameservers/{pk}`\nis being informed that the *parent* Domain should be looked up using the `domain_pk` kwarg\nfrom the URL:\n```python\n# serializers.py\n# (needed only if you want hyperlinks for nested relations on API)\nfrom rest_framework_nested.relations import NestedHyperlinkedRelatedField\n\nclass DomainSerializer(HyperlinkedModelSerializer):\n    class Meta:\n        model = Domain\n\n    nameservers = HyperlinkedIdentityField(\n        view_name='domain-nameservers-list',\n        lookup_url_kwarg='domain_pk'\n                        # ^-- Nameserver queryset will .get(domain_pk=domain_pk)\n                        #     being this value from URL kwargs\n    )\n\n\t## OR ##\n\n    nameservers = NestedHyperlinkedRelatedField(\n        many=True,\n        read_only=True,   # Or add a queryset\n        view_name='domain-nameservers-detail',\n        parent_lookup_kwargs={'domain_pk': 'domain__pk'}\n                            # ^-- Nameserver queryset will .filter(domain__pk=domain_pk)\n                            #     being domain_pk (ONE underscore) value from URL kwargs\n    )\n```\n\n**(optional)** If you want a little bit more control over the fields displayed for the nested relations while looking at the parent, you need a custom serializer using NestedHyperlinkedModelSerializer.\n```python\nfrom rest_framework.serializers import HyperlinkedModelSerializer\nfrom rest_framework_nested.serializers import NestedHyperlinkedModelSerializer\n\nclass NameserverSerializers(HyperlinkedModelSerializer):\n\tclass Meta:\n\t\tmodel = Nameserver\n\t\tfields = (...)\n\n\nclass DomainNameserverSerializers(NestedHyperlinkedModelSerializer):\n\tparent_lookup_kwargs = {\n\t\t'domain_pk': 'domain__pk',\n\t}\n\tclass Meta:\n\t\tmodel = Nameserver\n\t\tfields = ('url', ...)\n\n\nclass DomainSerializer(HyperlinkedModelSerializer):\n\tclass Meta:\n\t\tmodel = Domain\n\t\tfields = (..., 'nameservers')\n\n\tnameservers = DomainNameserverSerializers(many=True, read_only=True)\n```\n\n### Infinite-depth Nesting\n\nExample of nested router 3 levels deep.\nYou can use this same logic to nest routers as deep as you need.\nThis example ahead accomplishes the below URL patterns.\n```\n/clients/\n/clients/{pk}/\n/clients/{client_pk}/maildrops/\n/clients/{client_pk}/maildrops/{pk}/\n/clients/{client_pk}/maildrops/{maildrop_pk}/recipients/\n/clients/{client_pk}/maildrops/{maildrop_pk}/recipients/{pk}/\n```\n\n```python\n# urls.py\nrouter = DefaultRouter()\nrouter.register(r'clients', ClientViewSet, basename='clients')\n## generates:\n# /clients/\n# /clients/{pk}/\n\nclient_router = routers.NestedSimpleRouter(router, r'clients', lookup='client')\nclient_router.register(r'maildrops', MailDropViewSet, basename='maildrops')\n## generates:\n# /clients/{client_pk}/maildrops/\n# /clients/{client_pk}/maildrops/{pk}/\n\nmaildrops_router = routers.NestedSimpleRouter(client_router, r'maildrops', lookup='maildrop')\nmaildrops_router.register(r'recipients', MailRecipientViewSet, basename='recipients')\n## generates:\n# /clients/{client_pk}/maildrops/{maildrop_pk}/recipients/\n# /clients/{client_pk}/maildrops/{maildrop_pk}/recipients/{pk}/\n\nurlpatterns = [\n    path(r'', include(router.urls)),\n    path(r'', include(client_router.urls)),\n    path(r'', include(maildrops_router.urls)),\n]\n```\n\n```python\n# views.py\nclass ClientViewSet(viewsets.ViewSet):\n    serializer_class = ClientSerializer\n\n    def list(self, request,):\n        queryset = Client.objects.filter()\n        serializer = ClientSerializer(queryset, many=True)\n        return Response(serializer.data)\n\n    def retrieve(self, request, pk=None):\n        queryset = Client.objects.filter()\n        client = get_object_or_404(queryset, pk=pk)\n        serializer = ClientSerializer(client)\n        return Response(serializer.data)\n\n\nclass MailDropViewSet(viewsets.ViewSet):\n    serializer_class = MailDropSerializer\n\n    def list(self, request, client_pk=None):\n        queryset = MailDrop.objects.filter(client=client_pk)\n        serializer = MailDropSerializer(queryset, many=True)\n        return Response(serializer.data)\n\n    def retrieve(self, request, pk=None, client_pk=None):\n        queryset = MailDrop.objects.filter(pk=pk, client=client_pk)\n        maildrop = get_object_or_404(queryset, pk=pk)\n        serializer = MailDropSerializer(maildrop)\n        return Response(serializer.data)\n\n\nclass MailRecipientViewSet(viewsets.ViewSet):\n    serializer_class = MailRecipientSerializer\n\n    def list(self, request, client_pk=None, maildrop_pk=None):\n        queryset = MailRecipient.objects.filter(mail_drop__client=client_pk, mail_drop=maildrop_pk)\n        serializer = MailRecipientSerializer(queryset, many=True)\n        return Response(serializer.data)\n\n    def retrieve(self, request, pk=None, client_pk=None, maildrop_pk=None):\n        queryset = MailRecipient.objects.filter(pk=pk, mail_drop=maildrop_pk, mail_drop__client=client_pk)\n        maildrop = get_object_or_404(queryset, pk=pk)\n        serializer = MailRecipientSerializer(maildrop)\n        return Response(serializer.data)\n```\n\n```python\n# serializers.py\nclass ClientSerializer(HyperlinkedModelSerializer):\n    class Meta:\n        model = Client\n        fields = (...)\n\n\nclass MailDropSerializer(NestedHyperlinkedModelSerializer):\n    parent_lookup_kwargs = {\n        'client_pk': 'client__pk',\n    }\n    class Meta:\n        model = MailDrop\n        fields = (...)\n\n\nclass MailRecipientSerializer(NestedHyperlinkedModelSerializer):\n    parent_lookup_kwargs = {\n        'maildrop_pk': 'mail_drop__pk',\n        'client_pk': 'mail_drop__client__pk',\n    }\n    class Meta:\n        model = MailRecipient\n        fields = (...)\n```\n\n## Testing\n\nIn order to get started with testing, you will need to install [tox](https://tox.readthedocs.io/en/latest/).\nOnce installed, you can then run one environment locally, to speed up your development cycle:\n\n```\n$ tox -e py39-django3.1-drf3.11\n```\n\nOnce you submit a pull request, your changes will be run against many environments with GitHub Actions named CI.\n\n\n## License\n\nThis package is licensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\nand can undestand more at http://choosealicense.com/licenses/apache/ on the\nsidebar notes.\n\nApache Licence v2.0 is a MIT-like licence. This means, in plain English:\n- It's truly open source\n- You can use it as you wish, for money or not\n- You can sublicence it (change the licence!!)\n- This way, you can even use it on your closed-source project\nAs long as:\n- You cannot use the authors name, logos, etc, to endorse a project\n- You keep the authors copyright notices where this code got used, even on your closed-source project\n(come on, even Microsoft kept BSD notices on Windows about its TCP/IP stack :P)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falanjds%2Fdrf-nested-routers","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falanjds%2Fdrf-nested-routers","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falanjds%2Fdrf-nested-routers/lists"}