如何参数化DRF的API GET网址?

时间:2019-05-03 16:42:06

标签: django django-rest-framework django-urls

我用以下正则表达式url格式编写了一个与我想要的不兼容的API。我该怎么办?任何帮助表示赞赏。谢谢您。

我实际想要抛出的东西 KeyError at /app/check/ 'id' 错误 ...views.py in get_queryset, line 15

http://sample.com/app/check/?id=any_id_passed_into_the_url

我的工作原理

http://sample.com/app/check/id

我做什么

# app/urls.py
urlpatterns = [
    url(r'^app/', include('modul.urls', namespace='modul')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


# modul/urls.py
from django.conf.urls import url
from modul.views import OfferView

urlpatterns = [
    url(r'^check/(?P<id>[0-9]+)/$', OfferView.as_view(), name='id')
]

views.py

from rest_framework.response import Response

from app.models import App
from rest_framework import generics
from app.serializers import AppSerializer
from django.http import Http404
from IPython import embed


class OfferView(generics.RetrieveAPIView):
    serializer_class = AppSerializer
    lookup_field = 'id' # Here is line 15

    def get_queryset(self):
        id = self.kwargs['id']
        try:
            return App.objects.filter(id=id)
        except App.DoesNotExist:
            raise Http404

0 个答案:

没有答案