87 lines
3.4 KiB
Python
87 lines
3.4 KiB
Python
from rest_framework.permissions import AllowAny
|
|
from adrf.views import APIView
|
|
from rest_framework.response import Response
|
|
from rest_framework import status
|
|
from drf_yasg.utils import swagger_auto_schema
|
|
from drf_yasg import openapi
|
|
from ..models import Region
|
|
from ..serializers.region_serializers import RegionSimpleSerializer
|
|
|
|
|
|
class RegionListView(APIView):
|
|
"""获取地区级联数据"""
|
|
permission_classes = [AllowAny]
|
|
|
|
@swagger_auto_schema(
|
|
tags=['地区'],
|
|
operation_summary='获取地区列表',
|
|
operation_description='获取地区级联数据,支持按级别或父级编码查询',
|
|
manual_parameters=[
|
|
openapi.Parameter(
|
|
'level',
|
|
openapi.IN_QUERY,
|
|
description='地区级别(1=省份, 2=城市, 3=区县)',
|
|
type=openapi.TYPE_INTEGER,
|
|
required=False
|
|
),
|
|
openapi.Parameter(
|
|
'parent_code',
|
|
openapi.IN_QUERY,
|
|
description='父级地区编码,返回该编码下的子级地区',
|
|
type=openapi.TYPE_STRING,
|
|
required=False
|
|
),
|
|
],
|
|
responses={
|
|
200: openapi.Response(
|
|
description="Success",
|
|
schema=openapi.Schema(
|
|
type=openapi.TYPE_OBJECT,
|
|
properties={
|
|
'code': openapi.Schema(type=openapi.TYPE_INTEGER, example=200),
|
|
'message': openapi.Schema(type=openapi.TYPE_STRING, example='success'),
|
|
'data': openapi.Schema(
|
|
type=openapi.TYPE_ARRAY,
|
|
items=openapi.Schema(
|
|
type=openapi.TYPE_OBJECT,
|
|
properties={
|
|
'id': openapi.Schema(type=openapi.TYPE_INTEGER),
|
|
'name': openapi.Schema(type=openapi.TYPE_STRING),
|
|
'code': openapi.Schema(type=openapi.TYPE_STRING),
|
|
'level': openapi.Schema(type=openapi.TYPE_INTEGER),
|
|
'parent_id': openapi.Schema(type=openapi.TYPE_INTEGER),
|
|
'pinyin': openapi.Schema(type=openapi.TYPE_STRING),
|
|
}
|
|
)
|
|
),
|
|
}
|
|
)
|
|
),
|
|
}
|
|
)
|
|
async def get(self, request):
|
|
level = request.GET.get('level')
|
|
parent_code = request.GET.get('parent_code')
|
|
|
|
queryset = Region.objects.all()
|
|
|
|
if parent_code:
|
|
queryset = queryset.filter(parent__code=parent_code)
|
|
elif level:
|
|
try:
|
|
queryset = queryset.filter(level=int(level))
|
|
except (ValueError, TypeError):
|
|
return Response(
|
|
{"code": 400, "message": "level参数必须是整数", "data": None},
|
|
status=status.HTTP_400_BAD_REQUEST
|
|
)
|
|
else:
|
|
queryset = queryset.filter(level=1)
|
|
|
|
regions = [r async for r in queryset]
|
|
serializer = RegionSimpleSerializer(regions, many=True)
|
|
return Response(
|
|
{"code": 200, "message": "success", "data": await serializer.adata},
|
|
status=status.HTTP_200_OK
|
|
)
|