【问题标题】:Default HyperlinkedModelSerializer not finding the endpoints默认 HyperlinkedModelSerializer 未找到端点
【发布时间】: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


    【解决方案1】:

    很多天后,我想我找到了问题,所以我在这里发帖,以防我可以为别人节省那么多时间!

    问题基本上在于您如何处理您的路线。

    如果(您为每个应用程序使用路由器):
    然后你必须在注册路由器时添加一个对象的basename,并在序列化器中手动定义url字段。不要忘记添加应用程序的名称,例如“app:model”。例如:

    router.register(r'seasons', SeasonViewSet, basename='seasons')
    class SeasonSerializer(serializers.HyperlinkedModelSerializer):
        url = serializers.HyperlinkedIdentityField(view_name="accounts:seasons-detail")
        class Meta:
            model = Season
            fields = ('url', 'id', '...')
    

    如果(您使用 1 个路由器来嵌套来自不同应用的其余路由器):

    就像他们在here 中所做的那样。 然后您需要从 url 字段的“app:model”定义中删除该应用程序。

    我强烈建议使用 django-extesions 来使用 python manage.py show_urls 来了解项目中可用的端点。
    多亏了它,我才能够弄清楚发生了什么。看看我添加 API 根时的比较。

    (base) ➜  Betcomm git:(master) ✗ docker-compose exec app python manage.py show_urls | grep api/
    
    /api/accounts/profiles/ accounts.views.ProfileViewSet   accounts:profiles-list
    /api/accounts/profiles/<pk>/    accounts.views.ProfileViewSet   accounts:profiles-detail
    /api/accounts/season-profiles/  accounts.views.SeasonProfileViewSet accounts:season-profiles-list
    /api/accounts/season-profiles/<pk>/ accounts.views.SeasonProfileViewSet accounts:season-profiles-detail
    /api/accounts/users/    accounts.views.UserViewSet  accounts:users-list
    /api/accounts/users/<pk>/   accounts.views.UserViewSet  accounts:users-detail
    /api/seasons/seasons/   seasons.views.SeasonViewSet seasons:seasons-list
    /api/seasons/seasons/<pk>/  seasons.views.SeasonViewSet seasons:seasons-detail
    
    
    (base) ➜  Betcomm git:(master) ✗ docker-compose exec app python manage.py show_urls | grep api/
    
    /api/   rest_framework.routers.APIRootView  api-root
    /api/\.<format>/    rest_framework.routers.APIRootView  api-root
    /api/profiles/  accounts.views.ProfileViewSet   profiles-list
    /api/profiles/<pk>/ accounts.views.ProfileViewSet   profiles-detail
    /api/profiles/<pk>\.<format>/   accounts.views.ProfileViewSet   profiles-detail
    /api/profiles\.<format>/    accounts.views.ProfileViewSet   profiles-list
    /api/season-profiles/   accounts.views.SeasonProfileViewSet seasonprofiles-list
    /api/season-profiles/<pk>/  accounts.views.SeasonProfileViewSet seasonprofiles-detail
    /api/season-profiles/<pk>\.<format>/    accounts.views.SeasonProfileViewSet seasonprofiles-detail
    /api/season-profiles\.<format>/ accounts.views.SeasonProfileViewSet seasonprofiles-list
    /api/seasons/   seasons.views.SeasonViewSet seasons-list
    /api/seasons/<pk>/  seasons.views.SeasonViewSet seasons-detail
    /api/seasons/<pk>\.<format>/    seasons.views.SeasonViewSet seasons-detail
    /api/seasons\.<format>/ seasons.views.SeasonViewSet seasons-list
    /api/users/ accounts.views.UserViewSet  users-list
    /api/users/<pk>/    accounts.views.UserViewSet  users-detail
    /api/users/<pk>\.<format>/  accounts.views.UserViewSet  users-detail
    /api/users\.<format>/   accounts.views.UserViewSet  users-list
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-10
      • 2010-09-26
      • 2023-02-16
      • 1970-01-01
      • 2012-04-25
      • 1970-01-01
      相关资源
      最近更新 更多