I am trying to simply change my ModelSerializer to HyperlinkedModelSerializer to include the url to each of the objects listed in the ListView of the default Browsable API.
According to the docs, since I am using default 'pk' for the lookup, I just change the class I inherit the serializer from:
# class SeasonSerializer(serializers.ModelSerializer):
class SeasonSerializer(serializers.HyperlinkedModelSerializer):
# url = serializers.HyperlinkedIdentityField(
# view_name='season', lookup_field='pk') ---> Not needed according to docs but have also tried with this
class Meta:
model = Season
fields = ('id', 'url', 'years', 'active')
And add the context when instantiating it in the view:
class SeasonListView(APIView):
def get(self, request, *args, **kwargs):
queryset = Season.objects.all().order_by('years')
serializer = SeasonSerializer(
queryset, many=True, context={'request': request})
print('INFO: ', serializer)
permission_classes = [ ]
authentication_classes = [ ]
return Response({"Seasons": serializer.data})
class SeasonDetailView(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs['pk']
season = get_object_or_404(Season, pk=pk)
serializer = SeasonSerializer(season, context={'request': request})
# print('Data: ', serializer.data) --> this breaks
return Response(serializer.data)
And my endpoints are the same as when using ModelSerializer:
urlpatterns = [
path(r'seasons/', SeasonListView.as_view(), name='season-list'),
path(r'seasons/<int:pk>/', SeasonDetailView.as_view(), name='season-detail'),
]
The error is the following:
For http://localhost:8000/api/seasons/1/
Exception Type: ImproperlyConfigured
Exception Value:
Could not resolve URL for hyperlinked relationship using view name "season-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
And for http://localhost:8000/api/seasons/
Exception Type: ImproperlyConfigured
Exception Value:
Could not resolve URL for hyperlinked relationship using view name "season-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
What am I missing here?
Thanks!