【发布时间】:2020-07-22 02:48:23
【问题描述】:
我试图简单地将我的 ModelSerializer 更改为 HyperlinkedModelSerializer 以包含默认 Browsable API 的 ListView 中列出的每个对象的 url。
根据文档,由于我使用默认的 'pk' 进行查找,我只需更改继承序列化程序的类:
# 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')
并在视图中实例化时添加上下文:
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)
而且我的端点和使用 ModelSerializer 时一样:
urlpatterns = [
path(r'seasons/', SeasonListView.as_view(), name='season-list'),
path(r'seasons/<int:pk>/', SeasonDetailView.as_view(), name='season-detail'),
]
错误如下:
对于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.
对于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.
我在这里错过了什么?
谢谢!
【问题讨论】:
标签: django django-rest-framework