简体   繁体   中英

Could not resolve URL for hyperlinked relationship using view name “source-detail” Django

We are running into this issue on tables that have foreign key constraints. For the table creating this issue, we copied the table data exactly with no constraints, just the data to a new table and everything worked fine. However, we want to use the table with the relationships and real constraints.

Our models.py

class NewsSerialiser(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = News
        fields = ('news_id', 'news_source', 'news_title', 'news_description', 'news_publication_date', 'news_link')


class NewsViewSet(viewsets.ModelViewSet):

    queryset = News.objects.all()
    serializer_class = NewsSerialiser

Our URlS.py

# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'notes', NewsViewSet)

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('note.urls')),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^api/', include(router.urls)),
]

The issue we get:

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

Do you have a field named news_id in the model? And news_link might not worked. This example is worked for me.

class UserSerializer(serializers.HyperlinkedModelSerializer):

class Meta:
    model = User
    fields = (
        'username',
        ...,
        'url'
    )


class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

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