django rest django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name

使用: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']

 

posted @ 2024-05-20 16:18  小粉优化大师  阅读(41)  评论(0编辑  收藏  举报