Django 2.1,python 3.6,djangorestframework。
当我进入以下网址时,我可以看到我的数据(很棒!)http://127.0.0.1:8000/api/cards/1
这就是我在api页面上看到的-
HTTP 200 OK
Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{
"id": "1",
"card_title": "Hello"
},
]
我希望能够转到该网址以获取相同的数据-http://127.0.0.1:8000/api/cards/title/Hello
我该如何更新我的视图和URL?
基本网址
urlpatterns = [
...
path('api/cards/', include('cards.api.urls')),
]
cards.api.urls.py
urlpatterns = [
path('', CardListView.as_view()),
path('<str:pk>/', CardDetailView.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)
cards.api.views.py
class CardList(generics.ListCreateAPIView):
permission_classes = ()
queryset = Card.objects.all()
serializer_class = CardSerializer
class CardDetail(generics.RetrieveUpdateDestroyAPIView):
#permisssion_classes = (UserPermission,) # set the permission class
permission_classes = ()
queryset = Card.objects.all()
serializer_class = CardSerializer
我尝试将其添加到cards.api.urls.py path('api/cards/title/<str:pk>/', CardDetail.as_view()),
中,但它仍在查看id
变量而不是card_title
变量。
答案 0 :(得分:1)
我认为这会对您有所帮助,
# base urls.py
urlpatterns = [
...
path('api/', include('cards.api.urls')), # remove "cards/" from url
]
和
创建如下的新视图类 CardTitleDetail
并添加 lookup_field
属性
class CardTitleDetail(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'card_title'
permission_classes = ()
queryset = Card.objects.all()
serializer_class = CardSerializer
# cards.api.urls.py
urlpatterns = [
path('cards/', CardListView.as_view()), # add "cards/" to the url
path('cards/<str:pk>/', CardDetailView.as_view()), # add "cards/" to the url
path('cards/title/<str:card_title>/', CardTitleDetail.as_view()), # this is the new url
]
urlpatterns = format_suffix_patterns(urlpatterns)
注意
在整个数据库中, card_title
属性应为 unique
,否则将引发异常!
答案 1 :(得分:0)
您可以在您的cards.api.urls.py文件中添加另一个网址,以重定向到相同的api以获得相同的响应。
path('title/<str:pk>/', CardDetailView.as_view()),