简体   繁体   中英

Nested serializers: Could not resolve URL for hyperlinked relationship using view name

I've looked up this error but the answers posted earlier aren't working for me. I'm trying to set up nested serializers/views with HyperLinkedIdentityFields in Django Rest Framework but I'm getting the following error:

Could not resolve URL for hyperlinked relationship using view name "customers-report-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.

I have the following setup:

urls.py

urlpatterns = [
    path('<pk>/reports/<report_nr>/', ReportApiDetail.as_view(), name='customers-report-detail'),
    path('<pk>/reports/', ReportApiList.as_view(), name='customers-report-list'),
    path('<pk>/', CustomerApiDetail.as_view(), name='customer-detail'),
    path('', CustomerApiList.as_view(), name='customer-list'),

]

views.py

class CustomerApiList(generics.ListAPIView):
    queryset = Customer.objects.all()
    serializer_class = CustomerListSerializer


class CustomerApiDetail(generics.RetrieveAPIView):
    queryset = Customer.objects.all()
    serializer_class = CustomerDetailSerializer


class ReportApiList(generics.ListAPIView):
    serializer_class = ReportListSerializer
    queryset = Report.objects.all()

    def get_queryset(self, *args, **kwargs):
        pk = self.kwargs['pk']
        report_nr = self.kwargs['report_nr']
        return self.queryset.filter(customer_id=pk, report_nr=report_nr)

serializers.py

class ReportDetailSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Report
        fields = ['id', 'customer_id', 'report_nr', 'title', 'date_created', ]


class ReportListSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Report
        fields = ['url',]


class CustomerDetailSerializer(serializers.ModelSerializer):
    reports = serializers.HyperlinkedRelatedField(
        many=True,
        read_only=True,
        view_name='customers_report_detail'
    )

    class Meta:
        model = Customer
        fields = ['pk', 'name', 'reports',]


class CustomerListSerializer(serializers.HyperlinkedModelSerializer):
    # reports = serializers.SerializerMethodField('get_customer_orders')

    class Meta:
        model = Customer
        fields = ['url', 'pk', 'name', ]

In urls.py , try changing:

'<pk>/reports/<report_nr>/'
'<pk>/reports/'
'<pk>/'

To:

'<int:pk>/reports/<int:report_nr>/'
'<int:pk>/reports/'
'<int:pk>/'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM