Django REST框架:何时创建超链接资源和嵌套资源?如何发布嵌套资源? [英] Django REST Framework: when to create a hyperlinked resource and when nested resource? How to POST a nested resource?

查看:250
本文介绍了Django REST框架:何时创建超链接资源和嵌套资源?如何发布嵌套资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django REST框架构建REST Web API。事情进展顺利,但是我却遇到了嵌套资源的问题。起初,REST API中的所有关系都被超链接。例如,一个帖子如下所示:

  {
path:http:// api。 myproject.com/posts/1.json,
id:1,
author:http://api.myproject.com/users/broak.json,
image:/images/posts/cxyUzlPo.jpg,
header:我是谁?,
footer:我是冠军!,
date:2014-11-09 15:16,
喜欢:http://api.myproject.com/posts/1/likes.json,
评论:http://api.myproject.com/posts/1/comments.json,
likes_count:0,
comments_count:0
}

文章与作者(用户)之间的关系是超链接的。当你想创建一个新的帖子时,你需要指定一个正确的超链接到一个特定的用户 - 这很正常。



当调用帖子列表时,事情变得无效,因为您必须为每个帖子的每个作者添加一个额外的API调用。我通过使用NESTED资源而不是HYPERLINKED资源解决了这个问题,所以每个帖子现在都包含有关作者的所有信息。

  {
path:http://api.myproject.com/posts/1.json,
id:1,
author:{
email :broak@gmail.com
username:broak,
first_name:John,
last_name:Broak,
is_staff :False,
is_active:True,
last_login:02-26-2016
},
image:/ images / posts / cxyUzlPo
标题:我是谁?,
footer:我是冠军!,
date:2014-11-09 15 :16,
喜欢:http://api.myproject.com/posts/1/likes.json,
评论:http://api.myproject.com /posts/1/comments.json,
likes_count:0,
comments_count:0
}

我的第一个问题是:你有没有指导,是否应该创建一个嵌套数据st结构或具有超链接的单独端点。



我的第二个问题是:当我使用作者作为嵌套资源并且想要创建一个新的帖子时,我不想要指定所有关于作者的信息(用户名,电子邮件,...)。有没有办法只使用CREATE / UPDATE操作的用户链接?或修改一些东西,以便用户ID足够填写这个字段?

解决方案

如果我正确理解你的问题,在您检索数据时扩展作者,只需要在更新和创建时发送ID或URL。



1#它不是关于任何指导,而是完全取决于你对 api 将如何使用的要求。



2#所以你需要扩展你的 UserSerializer 并覆盖 to_internal_value 。示例代码可能看起来像

  class MyCustomSerializer(UserSerializer):
def to_internal_value(self,data):
#数据必须是有效的user-detail url
return serializers.HyperLinkedRelatedField(queryset = User.objects.all(),view_name ='user-detail')to_internal_value(data)

通知,您必须拥有能够使用HyperLinkedRelatedField的用户详细信息的端点。



所以如果你想要发送 ID ,那么示例代码可能看起来像



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ PrimaryKeyRelatedField(queryset = User.objects.all())to_internal_value(data)

不过我想在 POST / PUT / PATCH 中发送ForeignKey字段的一致性。 (始终是URL或ID)。



然后在您的代码中使用它,如

  class PostSerializer(serializers.HyperlinkedModelSerializer):
author = MyCustomSerializer()

class Meta:
model = Post

请参阅可写嵌套序列化程序到嵌套资源的 POST


I'm building a REST web API using the Django REST Framework. Things are going great, but I have, however stumbled upon a problem with nested resources. At first, all relationships in the REST API were hyperlinked. A post, for example, looked like this:

{
    "path": "http://api.myproject.com/posts/1.json",
    "id": 1,
    "author": "http://api.myproject.com/users/broak.json",
    "image": "/images/posts/cxyUzlPo.jpg",
    "header": "Who am I?",
    "footer": "I am a champion!",
    "date": "2014-11-09 15:16",
    "likes": "http://api.myproject.com/posts/1/likes.json",
    "comments": "http://api.myproject.com/posts/1/comments.json",
    "likes_count": 0,
    "comments_count": 0
}

The relationship between the post and the author (user) is hyperlinked. When you want to create a new post, you need to specify a correct hyperlink to a specific user - this works fine.

When calling a list of posts, things become inefficient, because you have to make an extra API call for every author for every post. I solved this by using NESTED resources instead of HYPERLINKED resources, so every post now contains all the information about the author.

{
    "path": "http://api.myproject.com/posts/1.json",
    "id": 1,
    "author": {
        "email": "broak@gmail.com"
        "username": "broak",
        "first_name: "John",
        "last_name": "Broak",
        "is_staff": False,
        "is_active": True,
        "last_login": "02-26-2016"
    },
    "image": "/images/posts/cxyUzlPo.jpg",
    "header": "Who am I?",
    "footer": "I am a champion!",
    "date": "2014-11-09 15:16",
    "likes": "http://api.myproject.com/posts/1/likes.json",
    "comments": "http://api.myproject.com/posts/1/comments.json",
    "likes_count": 0,
    "comments_count": 0
}

My first question is: do you have a guideline, whether I should create a nested data structure or a separate endpoint with hyperlink to it.

My second question is: when I use author as a nested resource and want to create a new post, I don't want to specify all the information about the author (username, e-mail, ...). Is there any way to just use a link to a user for the CREATE/UPDATE operation? Or modify something so that the user ID is enough to fill in this field?

解决方案

If i understood your question correctly, You want to have expanded author while you are retrieving the data and just want to send ID or URL in case of update and create.

1# It is not about any guideline and it totally depends on your requirement of how your api is going to be used.

2# So you need to extend your UserSerializer and override to_internal_value. Sample code might look like

class MyCustomSerializer(UserSerializer):
    def to_internal_value(self, data):
        # data must be valid user-detail url
        return serializers.HyperLinkedRelatedField(queryset=User.objects.all(), view_name='user-detail').to_internal_value(data)

Notice that you must have a Endpoint for user-detail in able to work with HyperLinkedRelatedField.

So If you want to be able to send ID then sample code might look like

class MyCustomSerializer(UserSerializer):
    # data must be valid user id
    def to_internal_value(self, data):
        return serializers.PrimaryKeyRelatedField(queryset=User.objects.all()).to_internal_value(data)

However i would like to keep consistency in sending ForeignKey field in POST/PUT/PATCH. (Always Either URL or ID).

then use it in your code like

class PostSerializer(serializers.HyperlinkedModelSerializer):
    author = MyCustomSerializer()

    class Meta:
        model = Post

Please see the documentation on Writable nested serializers to POST on a Nested resource.

这篇关于Django REST框架:何时创建超链接资源和嵌套资源?如何发布嵌套资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆