简体   繁体   中英

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

How to get this url working.. 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. Something like this:

pip install django-filter

add this to your rest framework settings: 'DEFAULT_FILTER_BACKENDS':['django_filters.rest_framework.DjangoFilterBackend']

Then in your TechViewSet you can add 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.

docs: https://www.django-rest-framework.org/api-guide/filtering/#djangofilterbackend

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM