Django Rest Framework:关联元素的URL [英] Django Rest Framework: URL for associated elements
问题描述
我已经创建了以下API端点,并且可以正常工作:
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).
为此,我将使用以下URL模式创建一个新的端点:
For that purpose, I would create a new endpoint with the following URL pattern:
/myApp/languages/<language_id>/countries/
如何用已经使用的 DefaultRouter
表示该模式?
How could I express that pattern with the DefaultRouter
that I'm already using?
推荐答案
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.
这篇关于Django Rest Framework:关联元素的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!