0

在给定以下模型的情况下,我正在尝试使用drf-nested-routers创建一个简单的嵌套 Django REST API:

# models.py
class Podcast(models.Model):
    title = models.CharField(max_length=125)

class Episode(models.Model):
    podcast = models.ForeignKey(Podcast, on_delete=models.CASCADE)
    title = models.CharField(max_length=125)

基于readme 域/名称服务器示例,我定义了以下路由器,期望 URL 结构如下:

/podcasts[/{podcast_pk}[/episodes[/{episode_pk}]]]
# urls.py
router = routers.DefaultRouter()
router.register(r'podcasts', PodcastViewSet)

episode_router = routers.NestedDefaultRouter(
    router, r'podcasts', lookup='podcast'
)
episode_router.register(
    r'episodes', EpisodeViewSet, basename='podcast-episodes'
)
# serializers.py
class PodcastSerializer(HyperlinkedModelSerializer):
    episodes = HyperlinkedIdentityField(
        view_name='podcast-episodes-list',
        lookup_url_kwarg='podcast_pk'
    )

    class Meta:
        model = Podcast
        fields = '__all__'

class EpisodeSerializer(NestedHyperlinkedModelSerializer):
    parent_lookup_kwargs = {
        'podcast_pk': 'podcast__pk',
    }

    class Meta:
        model = Episode
        fields = '__all__'
        # exclude = ('url',) # works without reference to self
# views.py
class PodcastViewSet(viewsets.ModelViewSet):
    queryset = Podcast.objects.all()
    serializer_class = PodcastSerializer

class EpisodeViewSet(viewsets.ModelViewSet):
    serializer_class = EpisodeSerializer

    def get_queryset(self):
        return Episode.objects.filter(
            podcast=self.kwargs['podcast_pk'],
        )

访问/podcasts/1/episodes/, 当url包含时,会引发以下错误:

Exception Type: ImproperlyConfigured at /podcasts/1/episodes/
Exception Value: Could not resolve URL for hyperlinked 
relationship using view name "episode-detail". You may 
have failed to include the related model in your API, 
or incorrectly configured the `lookup_field` attribute 
on this field.

为什么它不能识别正确的视图名称,或者我还缺少其他明显的东西

4

1 回答 1

0

在我的情况下,使用“id”而不是“pk”解决了我的问题。

parent_lookup_kwargs = {
    'podcast_pk': 'podcast_id',
}
于 2021-06-25T12:34:50.600 回答