无法使用视图名称“ source-detail” Django解析超链接关系的URL

时间:2018-06-21 15:13:36

标签: python django python-3.x django-rest-framework

我们在具有外键约束的表上遇到此问题。对于造成此问题的表,我们完全无限制地复制了表数据,只是将数据复制到新表中,并且一切正常。但是,我们希望将表与关系和实际约束一起使用。

我们的 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

我们的 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)),
]

我们遇到的问题:

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.

1 个答案:

答案 0 :(得分:0)

模型中是否有一个名为news_id的字段?而且news_link可能无效。 这个例子对我有用。

class UserSerializer(serializers.HyperlinkedModelSerializer):

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


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