如何配置viewsets.ModelViewSet以使用请求正文中传递的参数进行过滤。

我正在使用 DJANGO-REST-FRAMEWORK 构建 API。我试图使用传递给请求正文的参数来过滤后端,这是我的设置:


views.py


from .models import UsStatesG

from .serializer import UsStatesSerializer

from rest_framework import viewsets

from rest_framework.response import Response

from rest_framework.decorators import action


class 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.py


class 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.py


from django.contrib import admin

from django.urls import include, path, re_path

from api import views

from rest_framework.routers import DefaultRouter


router = 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.py


from rest_framework_gis.serializers import GeoFeatureModelSerializer

from .models import UsStatesG

我想在请求正文中传递参数(隐私问题)即正文 {"id": ["TX", "CA"]}

因为我对 DRF 还很陌生:


1-这是一个好方法吗?我是否使用了正确的视图类(视图集?)?


2-过滤模型传递从请求正文中获取的值的最佳(推荐方法)是什么?


注意:我正在处理地理空间数据,一个 PostgreSQL-PostGIS Back-end 。我也在使用rest_framework_gis


示例代码将不胜感激,特别推荐 urls.py 和views.py 的代码


斯蒂芬大帝
浏览 178回答 1
1回答

猛跑小猪

在你的 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')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python