**This is a work in progress. It "works for me" at www.apiregistro.com.br,
but I cannot warranty that it fully "works everywhere" yet. Join us on Gitter (below) if you need some help.**
# drf-nested-routers
[](https://gitter.im/alanjds/drf-nested-routers?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[](https://github.com/alanjds/drf-nested-routers/actions?query=workflow%3ACI+branch%3Amaster)
This package provides routers and fields to create nested resources in the [Django Rest Framework](http://django-rest-framework.org/)
Nested resources are needed for full REST URL structure, if one resource lives inside another.
The following example is about Domains and DNS Nameservers.
There are many domains, and each domain has many nameservers. The "nameserver" resource does not
exist without a domain, so you need it "nested" inside the domain.
## Requirements & Compatibility
- Python (3.8, 3.9, 3.10, 3.11, 3.12)
- Django (4.2, 5.0)
- Django REST Framework (3.14, 3.15)
It may work with lower versions, but since the release **0.93.5** is no more tested on CI for Python 3.6 or lower.<br/>
And 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.<br/>
Before that, the release **0.90.2** was tested also with DRF 2.4.3 up to 3.7.
## Installation
You can install this library using pip:
```pip install drf-nested-routers```
It 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.
## Quickstart
The desired URL signatures are:
```
/domains/ <- Domains list
/domains/{pk}/ <- One domain, from {pk}
/domains/{domain_pk}/nameservers/ <- Nameservers of domain from {domain_pk}
/domains/{domain_pk}/nameservers/{pk} <- Specific nameserver from {pk}, of domain from {domain_pk}
```
How to do it (example):
```python
# urls.py
from rest_framework_nested import routers
from views import DomainViewSet, NameserverViewSet
(...)
router = routers.SimpleRouter()
router.register(r'domains', DomainViewSet)
domains_router = routers.NestedSimpleRouter(router, r'domains', lookup='domain')
domains_router.register(r'nameservers', NameserverViewSet, basename='domain-nameservers')
# 'basename' is optional. Needed only if the same viewset is registered more than once
# Official DRF docs on this option: http://www.django-rest-framework.org/api-guide/routers/
urlpatterns = [
path(r'', include(router.urls)),
path(r'', include(domains_router.urls)),
]
```
```python
# views.py
## For Django' ORM-based resources ##
class NameserverViewSet(viewsets.ModelViewSet):
def get_queryset(self):
return Nameserver.objects.filter(domain=self.kwargs['domain_pk'])
## OR: non-ORM resources ##
class NameserverViewSet(viewsets.ViewSet):
def list(self, request, domain_pk=None):
nameservers = self.queryset.filter(domain=domain_pk)
(...)
return Response([...])
def retrieve(self, request, pk=None, domain_pk=None):
nameservers = self.queryset.get(pk=pk, domain=domain_pk)
(...)
return Response(serializer.data)
```
## Advanced
### Hyperlinks for Nested resources
**(optional)** If you need hyperlinks for nested relations, you need a custom serializer.
There you will inform how to access the *parent* of the instance being serialized when
building the *children* URL.
In the following example, an instance of Nameserver on `/domain/{domain_pk}/nameservers/{pk}`
is being informed that the *parent* Domain should be looked up using the `domain_pk` kwarg
from the URL:
```python
# serializers.py
# (needed only if you want hyperlinks for nested relations on API)
from rest_framework_nested.relations import NestedHyperlinkedRelatedField
class DomainSerializer(HyperlinkedModelSerializer):
class Meta:
model = Domain
nameservers = HyperlinkedIdentityField(
view_name='domain-nameservers-list',
lookup_url_kwarg='domain_pk'
# ^-- Nameserver queryset will .get(domain_pk=domain_pk)
# being this value from URL kwargs
)
## OR ##
nameservers = NestedHyperlinkedRelatedField(
many=True,
read_only=True, # Or add a queryset
view_name='domain-nameservers-detail',
parent_lookup_kwargs={'domain_pk': 'domain__pk'}
# ^-- Nameserver queryset will .filter(domain__pk=domain_pk)
# being domain_pk (ONE underscore) value from URL kwargs
)
```
**(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.
```python
from rest_framework.serializers import HyperlinkedModelSerializer
from rest_framework_nested.serializers import NestedHyperlinkedModelSerializer
class NameserverSerializers(HyperlinkedModelSerializer):
class Meta:
model = Nameserver
fields = (...)
class DomainNameserverSerializers(NestedHyperlinkedModelSerializer):
parent_lookup_kwargs = {
'domain_pk': 'domain__pk',
}
class Meta:
model = Nameserver
fields = ('url', ...)
class DomainSerializer(HyperlinkedModelSerializer):
class Meta:
model = Domain
fields = (..., 'nameservers')
nameservers = DomainNameserverSerializers(many=True, read_only=True)
```
### Infinite-depth Nesting
Example of nested router 3 levels deep.
You can use this same logic to nest routers as deep as you need.
This example ahead accomplishes the below URL patterns.
```
/clients/
/clients/{pk}/
/clients/{client_pk}/maildrops/
/clients/{client_pk}/maildrops/{pk}/
/clients/{client_pk}/maildrops/{maildrop_pk}/recipients/
/clients/{client_pk}/maildrops/{maildrop_pk}/recipients/{pk}/
```
```python
# urls.py
router = DefaultRouter()
router.register(r'clients', ClientViewSet, basename='clients')
## generates:
# /clients/
# /clients/{pk}/
client_router = routers.NestedSimpleRouter(router, r'clients', lookup='client')
client_router.register(r'maildrops', MailDropViewSet, basename='maildrops')
## generates:
# /clients/{client_pk}/maildrops/
# /clients/{client_pk}/maildrops/{pk}/
maildrops_router = routers.NestedSimpleRouter(client_router, r'maildrops', lookup='maildrop')
maildrops_router.register(r'recipients', MailRecipientViewSet, basename='recipients')
## generates:
# /clients/{client_pk}/maildrops/{maildrop_pk}/recipients/
# /clients/{client_pk}/maildrops/{maildrop_pk}/recipients/{pk}/
urlpatterns = [
path(r'', include(router.urls)),
path(r'', include(client_router.urls)),
path(r'', include(maildrops_router.urls)),
]
```
```python
# views.py
class ClientViewSet(viewsets.ViewSet):
serializer_class = ClientSerializer
def list(self, request,):
queryset = Client.objects.filter()
serializer = ClientSerializer(queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None):
queryset = Client.objects.filter()
client = get_object_or_404(queryset, pk=pk)
serializer = ClientSerializer(client)
return Response(serializer.data)
class MailDropViewSet(viewsets.ViewSet):
serializer_class = MailDropSerializer
def list(self, request, client_pk=None):
queryset = MailDrop.objects.filter(client=client_pk)
serializer = MailDropSerializer(queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None, client_pk=None):
queryset = MailDrop.objects.filter(pk=pk, client=client_pk)
maildrop = get_object_or_404(queryset, pk=pk)
serializer = MailDropSerializer(maildrop)
return Response(serializer.data)
class MailRecipientViewSet(viewsets.ViewSet):
serializer_class = MailRecipientSerializer
def list(self, request, client_pk=None, maildrop_pk=None):
queryset = MailRecipient.objects.filter(mail_drop__client=client_pk, mail_drop=maildrop_pk)
serializer = MailRecipientSerializer(queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None, client_pk=None, maildrop_pk=None):
queryset = MailRecipient.objects.filter(pk=pk, mail_drop=maildrop_pk, mail_drop__client=client_pk)
maildrop = get_object_or_404(queryset, pk=pk)
serializer = MailRecipientSerializer(maildrop)
return Response(serializer.data)
```
```python
# serializers.py
class ClientSerializer(HyperlinkedModelSerializer):
class Meta:
model = Client
fields = (...)
class MailDropSerializer(NestedHyperlinkedModelSerializer):
parent_lookup_kwargs = {
'client_pk': 'client__pk',
}
class Meta:
model = MailDrop
fields = (...)
class MailRecipientSerializer(NestedHyperlinkedModelSerializer):
parent_lookup_kwargs = {
'maildrop_pk': 'mail_drop__pk',
'client_pk': 'mail_drop__client__pk',
}
class Meta:
model = MailRecipient
fields = (...)
```
## Testing
In order to get started with testing, you will need to install [tox](https://tox.readthedocs.io/en/latest/).
Once installed, you can then run one environment locally, to speed up your development cycle:
```
$ tox -e py39-django3.1-drf3.11
```
Once you submit a pull request, your changes will be run against many environments with GitHub Actions named CI.
## License
This package is licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
and can undestand more at http://choosealicense.com/licenses/apache/ on the
sidebar notes.
Apache Licence v2.0 is a MIT-like licence. This means, in plain English:
- It's truly open source
- You can use it as you wish, for money or not
- You can sublicence it (change the licence!!)
- This way, you can even use it on your closed-source project
As long as:
- You cannot use the authors name, logos, etc, to endorse a project
- You keep the authors copyright notices where this code got used, even on your closed-source project
(come on, even Microsoft kept BSD notices on Windows about its TCP/IP stack :P)
Raw data
{
"_id": null,
"home_page": "https://github.com/alanjds/drf-nested-routers",
"name": "drf-nested-routers",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": null,
"author": "Alan Justino et al.",
"author_email": "alan.justino@yahoo.com.br",
"download_url": "https://files.pythonhosted.org/packages/1e/24/9e6a070dc491a416c93e4ec41950c7ea66d6a63b8db8d8abc0c128355978/drf-nested-routers-0.94.1.tar.gz",
"platform": null,
"description": "**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[](https://gitter.im/alanjds/drf-nested-routers?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)\n[](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 & Compatibility\n\n- Python (3.8, 3.9, 3.10, 3.11, 3.12)\n- Django (4.2, 5.0)\n- Django REST Framework (3.14, 3.15)\n\nIt may work with lower versions, but since the release **0.93.5** is no more tested on CI for Python 3.6 or lower.<br/>\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.<br/>\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/ <- Domains list\n/domains/{pk}/ <- One domain, from {pk}\n/domains/{domain_pk}/nameservers/ <- Nameservers of domain from {domain_pk}\n/domains/{domain_pk}/nameservers/{pk} <- 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",
"bugtrack_url": null,
"license": "Apache",
"summary": "Nested resources for the Django Rest Framework",
"version": "0.94.1",
"project_urls": {
"Homepage": "https://github.com/alanjds/drf-nested-routers"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "4ea2313a95268ffae9773a59aeb15c3f6932d4c905616d4797b371e6257fc8f9",
"md5": "3f7a9f6e77c1c3461f6489e1cc50c0d7",
"sha256": "3a8ec45a025c0f39188ec1ec415244beb875a6f4db87911a1f5a606d09b68c9f"
},
"downloads": -1,
"filename": "drf_nested_routers-0.94.1-py2.py3-none-any.whl",
"has_sig": false,
"md5_digest": "3f7a9f6e77c1c3461f6489e1cc50c0d7",
"packagetype": "bdist_wheel",
"python_version": "py2.py3",
"requires_python": ">=3.8",
"size": 36260,
"upload_time": "2024-05-10T22:36:53",
"upload_time_iso_8601": "2024-05-10T22:36:53.092750Z",
"url": "https://files.pythonhosted.org/packages/4e/a2/313a95268ffae9773a59aeb15c3f6932d4c905616d4797b371e6257fc8f9/drf_nested_routers-0.94.1-py2.py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "1e249e6a070dc491a416c93e4ec41950c7ea66d6a63b8db8d8abc0c128355978",
"md5": "7f7773ce31ded5bb60d0c3207a8dde63",
"sha256": "2b846385ed95c9f17bf4242db3b264ac826b5af00dda6c737d3fe7cc7bf2c7db"
},
"downloads": -1,
"filename": "drf-nested-routers-0.94.1.tar.gz",
"has_sig": false,
"md5_digest": "7f7773ce31ded5bb60d0c3207a8dde63",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 18347,
"upload_time": "2024-05-10T22:36:55",
"upload_time_iso_8601": "2024-05-10T22:36:55.553424Z",
"url": "https://files.pythonhosted.org/packages/1e/24/9e6a070dc491a416c93e4ec41950c7ea66d6a63b8db8d8abc0c128355978/drf-nested-routers-0.94.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-05-10 22:36:55",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "alanjds",
"github_project": "drf-nested-routers",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"requirements": [],
"tox": true,
"lcname": "drf-nested-routers"
}