0

I am attempting to use drf-nested-routers to create a simple nested Django REST API given the following models:

# 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)

Based on the readme domains/nameservers example, I have the following routers defined, expecting a URL structure like:

/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'],
        )

Accessing /podcasts/1/episodes/, when url is included, raises the following error:

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.

Why does it not identify the correct view name, or is there something else obvious I am missing

Kjell-Bear
  • 759
  • 1
  • 5
  • 12

1 Answers1

0

In my case using 'id' instead of 'pk' is solved my problem.

parent_lookup_kwargs = {
    'podcast_pk': 'podcast_id',
}