使用Djang将detail API视图设置为str而不是pk

2024-09-25 08:29:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经将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())
]

Tags: namepy程序名称视图apiurl序列化
1条回答
网友
1楼 · 发布于 2024-09-25 08:29:45

您应该使用lookup_field。验证/api/是否显示国家列表。然后尝试/api/<country_name>/,其中country_name是Country实例之一的名称。在

class CountryDetailView(RetrieveAPIView):
    queryset = Country.objects.all()
    serializer_class = CountrySerializer
    lookup_field = 'name'

class CountrySerializer(serializers.ModelSerializer):
    class Meta:
        model = Country
        ...
        lookup_field = 'name'

相关问题 更多 >