我正在为Django中的特定对象成功检索所有记录。
我的url.py是path('city/', views.TestListCity.as_view())
我从邮递员那里得到:http://192.168.99.100:8080/collection/city,它返回所有记录。
示例:
{
"id": 3,
"name": "Bor",
"region": {
"id": 2,
"name": "Sun"
}
},
现在,我要过滤具有列名称的记录。
我尝试过:
urls.py
path('city/(?P<name>.+)/$', views.TestListCity.as_view()),
views.py
class TestListCity(generics.RetrieveAPIView):
serializer_class = TestListCitySerializer
def get_queryset(self):
name = self.kwargs['name']
return City.objects.filter(name=name)
我尝试GET:
http://192.168.99.100:8080/collection/city?name=Bor
但随后是404:
<title>Page not found at /collection/city</title>
我还尝试了第二种方法:
urls.py
path('city/<str:name>/', views.TestListCity.as_view())
views.py
class TestListCity(generics.RetrieveAPIView):
serializer_class = TestListCitySerializer
queryset = City.objects.all()
lookup_field = 'name'
但反应完全一样。
答案 0 :(得分:0)
如果要使用下面的URL(或等效的URL),其中字符串是url匹配的一部分:
path('city/<str:name>/$', views.TestListCity.as_view()),
然后致电:
http://192.168.99.100:8080/collection/city/Bor/
代替:
http://192.168.99.100:8080/collection/city?name=Bor
后一个通过Bor
作为name
请求的GET
参数的值,即,您将需要使用类似name = self.request.GET.get('name')
的方法来获得{{ 1}}参数。它不会成为URL匹配的一部分。
答案 1 :(得分:0)
这是因为您使用了path()
,并且想要一个正则表达式(re_path()
)。
更改此:
from django.urls import path
path('city/(?P<name>.+)/$', views.TestListCity.as_view()),
收件人:
from django.urls import re_path
re_path('city/(?P<name>.+)/$', views.TestListCity.as_view()),
这应该有效。也许/
是可选的,例如:'city/(?P<name>.+)/?$'