Reputation: 7940
I have the following API endpoints already created and working fine:
urls.py:
router = DefaultRouter()
router.register(r'countries', views.CountriesViewSet,
base_name='datapoints')
router.register(r'languages', views.LanguageViewSet,
base_name='records')
Now, I need to create a new endpoint, where I can retrieve the countries associated with one language (let's suppose that one country has just one associated language).
For that purpose, I would create a new endpoint with the following URL pattern:
/myApp/languages/<language_id>/countries/
How could I express that pattern with the DefaultRouter
that I'm already using?
Upvotes: 0
Views: 88
Reputation: 5968
You can benefit from DRF routers' extra actions capabilities and especially the @action
method decorator:
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.generics import get_object_or_404
from .serializers import CountrySerializer
class LanguageViewSet(ModelViewSet):
# ...
@action(detail=True, methods=['get']):
def countries(self, request, pk=None):
language = get_object_or_404(Language, pk=pk)
# Note:
# In the next line, have in mind the
# related_name
# specified in models
# between Country & Language
countries = language.countries.all()
# ___________________^
serializer = CountrySerializer(countries, many=True)
return Response(data=serializer.data)
Having this, your current router specification should stay the same and you will have your desired route already registered.
Upvotes: 1