我正在使用 DJANGO-REST-FRAMEWORK 构建 API。我试图使用传递给请求正文的参数来过滤后端,这是我的设置:views.pyfrom .models import UsStatesGfrom .serializer import UsStatesSerializerfrom rest_framework import viewsetsfrom rest_framework.response import Responsefrom rest_framework.decorators import actionclass StatesViewSet(viewsets.ModelViewSet): queryset = UsStatesG.objects.all() serializer_class = UsStatesSerializer @action(detail=False) def get_by_id(self, request): body = request.body.decode('utf-8') body = json.loads(body) state_list = UsStatesG.objects.filter(st_abbr__in=body['id']) serializer = self.get_serializer(state_list, many=True) return Response(serializer.data)models.pyclass UsStatesG(models.Model): st_fips = models.CharField(primary_key=True, max_length=2, unique=True) geom = models.MultiPolygonField(blank=False, null=False) objectid = models.BigIntegerField(blank=False, null=False) st_name = models.CharField(max_length=50, blank=False, null=False) st_abbr = models.CharField(max_length=2, blank=False, null=False, unique=True) class Meta: managed = False db_table = 'US_States_G'urls.pyfrom django.contrib import adminfrom django.urls import include, path, re_pathfrom api import viewsfrom rest_framework.routers import DefaultRouterrouter = DefaultRouter()router.register(r'states', views.StatesViewSet)router.register(r'states/q', views.StatesViewSet.get_by_id, basename='UsStatesG')urlpatterns = [ path('api/location/v1/', include(router.urls)), serializer.pyfrom rest_framework_gis.serializers import GeoFeatureModelSerializerfrom .models import UsStatesG我想在请求正文中传递参数(隐私问题)即正文 {"id": ["TX", "CA"]}因为我对 DRF 还很陌生:1-这是一个好方法吗?我是否使用了正确的视图类(视图集?)?2-过滤模型传递从请求正文中获取的值的最佳(推荐方法)是什么?注意:我正在处理地理空间数据,一个 PostgreSQL-PostGIS Back-end 。我也在使用rest_framework_gis示例代码将不胜感激,特别推荐 urls.py 和views.py 的代码
1 回答
猛跑小猪
TA贡献1858条经验 获得超8个赞
在你的 urls.py 中,你配置了一些错误的东西:
router.register(r'states/q', views.StatesViewSet.get_by_id, basename='UsStatesG')
您想要的视图已包含在该行中:
router.register(r'states', views.StatesViewSet)
默认情况下端点是states/get_by_id/
. 如果你希望端点是states/q
,你可以在装饰器中配置它@action
。
@action(detail=False, url_path='q')
添加回答
举报
0/150
提交
取消