我正在使用 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 的代码
猛跑小猪
相关分类