使用:HyperlinkedRelatedField 報錯資訊
django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "fk_table:album_list".
You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
原因:
因為我配置顯示資料的URL導致的 # url urlpatterns = [ path('album/', include([ path('list/', AlbumList.as_view(), name='album_list'), ])), ] # serializers class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='fk_table:album_list') # album_list配置有問題,沒有pk的識別 class Meta: model = Album fields = ['album_name', 'artist', 'tracks']
解決方法
# url urlpatterns = [ path('album/', include([ path('list/', AlbumList.as_view(), name='album_list'), path('edit/<int:pk>/', AlbumList.as_view(), name='album_edit'), ])), ] # serializers class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='fk_table:album_edit') class Meta: model = Album fields = ['album_name', 'artist', 'tracks']