Django rest框架:hypeling引用的实体

2024-10-03 11:17:05 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的项目中,我使用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/"
        }, 
    [---]

Tags: 用户pyapihttptitle地址blogcontent
1条回答
网友
1楼 · 发布于 2024-10-03 11:17:05

当需要对相关对象进行超链接时,应该使用HyperlinkedRelatedField。当需要针对当前对象(序列化程序上的url字段)进行超链接时,应该使用HyperlinkedIdentityField。你知道吗

class BlogArticleSerializer(serializers.HyperlinkedModelSerializer):
    author = serializers.HyperlinkedRelatedField(view_name='user-detail', format='json')

    class Meta:
        model = BlogArticle
        fields = ('title', 'blog_content', 'author')

相关问题 更多 >