在我的项目中,我使用Django rest框架通过公共API公开所有BlogArticle实体。你知道吗
每个BlogArticle都有一个author
字段,它引用一个Django用户。我想用超链接来模拟这种关系。你知道吗
为此,我补充说:
在网址.py地址:
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'blogarticles', BlogArticleViewSet)
在视图.py地址:
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
class BlogArticleViewSet(viewsets.ModelViewSet):
queryset = BlogArticle.objects.all()
serializer_class = BlogArticleSerializer
在序列化程序.py地址:
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
class BlogArticleSerializer(serializers.HyperlinkedModelSerializer):
author = serializers.HyperlinkedIdentityField(view_name='user-detail', format='json')
class Meta:
model = BlogArticle
fields = ('title', 'blog_content', 'author')
一切正常,但不是超链接的网址。你知道吗
结果是:
HTTP 200 OK
Content-Type: application/json
Vary: Accept
Allow: GET, POST, HEAD, OPTIONS
{
"count": 21,
"next": "http://127.0.0.1:8000/api/blogarticles/?page=2",
"previous": null,
"results": [
{
"title": "text",
"blog_content": "content",
"author": "http://127.0.0.1:8000/api/users/1/"
},
{
"title": "boh",
"blog_content": "aa",
"author": "http://127.0.0.1:8000/api/users/2/"
},
[---]
前两篇博客文章显然是由两个不同的用户写的,但是用户总是相同的(因为通过调用第二个url,我得到了404响应)。你知道吗
我期待的是:
HTTP 200 OK
Content-Type: application/json
Vary: Accept
Allow: GET, POST, HEAD, OPTIONS
{
"count": 21,
"next": "http://127.0.0.1:8000/api/blogarticles/?page=2",
"previous": null,
"results": [
{
"title": "text",
"blog_content": "content",
"author": "http://127.0.0.1:8000/api/users/1/"
},
{
"title": "boh",
"blog_content": "aa",
"author": "http://127.0.0.1:8000/api/users/1/"
},
[---]
当需要对相关对象进行超链接时,应该使用
HyperlinkedRelatedField
。当需要针对当前对象(序列化程序上的url
字段)进行超链接时,应该使用HyperlinkedIdentityField
。你知道吗相关问题 更多 >
编程相关推荐