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



我们在具有外键约束的表上遇到了这个问题。对于产生此问题的表,我们完全没有约束地复制了表数据,只是将数据复制到新表中,一切正常。但是,我们希望使用具有关系和实际约束的表。

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

模型中是否有名为 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

相关内容

最新更新