Django rest framework 使用视图集封装相关端点
我喜欢ViewSet可以使用路由器的方式,并且可以将多个端点保持在一起,而不必分别在url.py中注册它们 我正在实现映射,以发送到UI,将存储在数据库中的短代码映射到显示名称(来自TextChoices)。布景会越来越大Django rest framework 使用视图集封装相关端点,django-rest-framework,Django Rest Framework,我喜欢ViewSet可以使用路由器的方式,并且可以将多个端点保持在一起,而不必分别在url.py中注册它们 我正在实现映射,以发送到UI,将存储在数据库中的短代码映射到显示名称(来自TextChoices)。布景会越来越大 from .models import AssetTypes, Countries, Exchanges permission_classes = [permissions.IsAuthenticated] @action(detail=False, m
from .models import AssetTypes, Countries, Exchanges
permission_classes = [permissions.IsAuthenticated]
@action(detail=False, methods=['GET'])
def asset_types(self, request, pk=None):
"""
API endpoint that gets the mappings from the two character asset type id that is stored in the database and the
text to be displayed.
"""
return JsonResponse(choice_to_json('asset_type', AssetTypes))
@action(detail=False, methods=['GET'])
def exchanges(self, request, pk=None):
"""
API endpoint that gets the mappings from the one character exchange id at is stored in the database and the
text to be displayed.
"""
return JsonResponse(choice_to_json('exchange', Exchanges))
@action(detail=False, methods=['GET'])
def countries(self, request, pk=None):
"""
API endpoint that gets the mappings from the two character country id that is stored in the database and the
text to be displayed.
"""
return JsonResponse(choice_to_json('country', Countries))
这三个函数返回的正是我想要的,但是如果调用方恰好使用了父url,那么就会出现错误,因为我没有查询集或支持模型
/mapping/counrties # Works as expected
/mapping # No implementation so gets exception
是否有合适的方法使用视图集实现此方案,或者我必须返回到@api\u view并分别注册每个视图?为此,您可以使用APIView。为此,您可以使用APIView。