Django Rest Framework: URL for associated elements

百般思念 提交于 2021-02-08 11:53:25

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/57943000/django-rest-framework-url-for-associated-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!