我已经将API列表视图设置为url“API/”,我想将detail(RetrieveAPI)视图从url“API/”pk“/”更改为“API/”name“/,其中name是模型中的字段。在
我试过各种组合
lookup_url_kwarg = 'name'
以及
^{pr2}$在我的序列化程序.py以及视图.py,但要么我得到404响应,要么url仍然是api//。另外,如果字段是一个字符串,我是否必须在我的URL中包括引号?任何洞察力都太好了!在
在序列化程序.py公司名称:
class CountrySerializer(serializers.ModelSerializer):
class Meta:
model = Country
fields =('name', 'topLevelDomain', 'alpha2Code', 'alpha3Code', 'callingCodes',
'capital', 'altSpellings', 'region', 'subregion', 'population', 'latlng',
'demonym', 'timezones', 'borders', 'nativeName', 'numericCode',
'currencies', 'translations', 'flag', 'regionalBlocs', 'cioc')
lookup_field = 'name'
在视图.py公司名称:
class CountryListView(ListAPIView):
queryset = Country.objects.all()
serializer_class = CountrySerializer
class CountryDetailView(RetrieveAPIView):
queryset = Country.objects.all()
serializer_class = CountrySerializer
#lookup_url_kwarg = 'name'
在网址.py公司名称:
urlpatterns = [
path('', CountryListView.as_view()),
path('<name>/', CountryDetailView.as_view())
]
您应该使用
lookup_field
。验证/api/
是否显示国家列表。然后尝试/api/<country_name>/
,其中country_name是Country
实例之一的名称。在相关问题 更多 >
编程相关推荐