[英]How to provide a parameter to a router in django rest API?
So the url I am trying to achieve looks like this:所以我试图实现的网址如下所示:
127.0.01:8000/api/tech/?belongs=id
My router looks like this:我的路由器看起来像这样:
router = routers.DefaultRouter()
router.register('tech', TechViewSet, basename="tech")
urlpatterns = [
path('', include(router.urls)),
re_path(r'^tech/(?P<belongs>)$', include(router.urls), name="info"),
My viewset looks like this (Also has a retrieve and list functions):我的视图集看起来像这样(还有一个检索和列表功能):
@action(detail=True, url_path='^tech/(?P<belongs>)$', methods=['get'])
def retrieve1(self, request, group=None):
pass
And the router is obviously included in urls.py of main project并且路由器显然包含在主项目的 urls.py 中
How to get this url working.. 127.0.01:8000/api/tech/?belongs=id如何让这个网址工作.. 127.0.01:8000/api/tech/?belongs=id
Please help.请帮忙。 and Im sorry, I'm still learning and the routing part is confusing..
对不起,我还在学习,路由部分令人困惑..
Thankyou so much非常感谢
It's a little tricky without knowing your model structure.在不知道您的模型结构的情况下,这有点棘手。 But if you're using your
get
parameters for filtering you can use django_filters
to do the heavy lifting for you.但是,如果您使用
get
参数进行过滤,则可以使用django_filters
为您完成繁重的工作。 Something like this:像这样的东西:
pip install django-filter
add this to your rest framework settings: 'DEFAULT_FILTER_BACKENDS':['django_filters.rest_framework.DjangoFilterBackend']
将此添加到您的休息框架设置:
'DEFAULT_FILTER_BACKENDS':['django_filters.rest_framework.DjangoFilterBackend']
Then in your TechViewSet
you can add filterset_fields
:然后在您的
TechViewSet
您可以添加filterset_fields
:
class TechViewSet:
<your other variables>
filterset_fields = ['belongs',]
you can then add query parameters ?belongs=<some_id>
to your url and your results will be filtered.然后,您可以将查询参数
?belongs=<some_id>
到您的网址,您的结果将被过滤。
docs: https://www.django-rest-framework.org/api-guide/filtering/#djangofilterbackend文档: https : //www.django-rest-framework.org/api-guide/filtering/#djangofilterbackend
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.