在DRF中使用HyperlinkedModelSerializer有什么好處?

[英]What is the benefit of using a HyperlinkedModelSerializer in DRF?


In reference to this link, I've seen plenty of examples of using a HyperlinkedModelSerializer in Django Rest Framework. It says:

在參考這個鏈接時,我已經看到很多在Django Rest Framework中使用HyperlinkedModelSerializer的例子。它說:

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys.

HyperlinkedModelSerializer類與ModelSerializer類類似,不同之處在於它使用超鏈接來表示關系,而不是主鍵。

My question is, what is the use case/benefit of using them vs a regular Model Serializer?

我的問題是,使用它們與常規模型序列化器的用例/好處是什么?

3 个解决方案

#1


18  

The only difference is, as in citation you included, that primary and foreign keys are represented by URLs that point to those resources, instead of just actual key values.

唯一的區別在於,如您所引用的那樣,主鍵和外鍵由指向這些資源的URL表示,而不僅僅是實際的鍵值。

The benefit is that you will not have to construct resource URLs in your frontend when you want to retrieve related objects.

這樣做的好處是,當您想要檢索相關對象時,您不必在前端構建資源URL。

Another thing entirely is nested representations which allows you to inline related objects in your serializer output. This can be combined with both ModelSerializer and HyperlinkedModelSerializer when you think that it is more convenient for the API consumer to have related items right away instead of making additional requests to retrieve them.

完全另一件事是嵌套表示,它允許您在序列化器輸出中內聯相關對象。當您認為API使用者更方便地擁有相關項目而不是提供其他請求來檢索它們時,可以將它與ModelSerializer和HyperlinkedModelSerializer結合使用。

Nested representations can be implemented via the Meta.depth option or by using the related model's serializer instead of a RelatedField.

嵌套表示可以通過Meta.depth選項或使用相關模型的序列化程序而不是相關字段來實現。

As @xleon said in his comment using URLs as keys makes it easier for other developers to understand your API.

正如@xleon在評論中所說的那樣,使用URL作為鍵使其他開發人員更容易理解您的API。

#2


5  

We need to implement relationship between entities in Web API design. There are several ways to do that (as mentions on DRF documentation):

我們需要在Web API設計中實現實體之間的關系。有幾種方法可以做到這一點(如DRF文檔中所述):

  • Using primary keys.
  • 使用主鍵。
  • Using hyperlinking between entities.
  • 在實體之間使用超鏈接。
  • Using a unique identifying slug field on the related entity.
  • 在相關實體上使用唯一的識別段塞字段。
  • Using the default string representation of the related entity.
  • 使用相關實體的默認字符串表示形式。
  • Nesting the related entity inside the parent representation.
  • 將相關實體嵌套在父表示中。
  • Some other custom representation
  • 一些其他自定義表示

The HyperlinkedModelSerializer has the following differences from ModelSerializer:

HyperlinkedModelSerializer與ModelSerializer有以下不同之處:

  • It does not include the id field by default.
  • 默認情況下,它不包括id字段。
  • It includes a url field, using HyperlinkedIdentityField.
  • 它包含一個url字段,使用HyperlinkedIdentityField。
  • Relationships use HyperlinkedRelatedField, instead of PrimaryKeyRelatedField.
  • 關系使用HyperlinkedRelatedField而不是PrimaryKeyRelatedField。

A simple example:

一個簡單的例子:

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'groups')


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ('url', 'name')

bash> http -a admin:yourpassword http://127.0.0.1:8000/users/

bash> http -a admin:yourpassword http://127.0.0.1:8000/users/

 "results": [
        {
            "email": "admin@min.com",
            "groups": [
                "http://127.0.0.1:8000/groups/1/",
                "http://127.0.0.1:8000/groups/2/"
            ],
            "url": "http://127.0.0.1:8000/users/1/",
            "username": "admin"
        }
    ]

But if you change

但如果你改變了

class UserSerializer(serializers.ModelSerializer):
        class Meta:
            model = User
            fields = ('url', 'username', 'email', 'groups')

The result will be:

結果將是:

   "results": [
        {
            "email": "admin@min.com",
            "groups": [
                1,
                2
            ],
            "url": "http://127.0.0.1:8000/users/1/",
            "username": "admin"
        }
    ]

#3


0  

One cost of HyperlinkedModelSerializers that should be noted is that if your API supports filtering or ordering via query parameters in the URL it is a bit more difficult for your frontend consumer to use the hyperlinked url fields for constructing query params because they have to parse out the pk from the URL rather than having the pk directly available.

應該注意的HyperlinkedModelSerializers的一個代價是,如果您的API支持通過URL中的查詢參數進行過濾或排序,那么您的前端使用者使用超鏈接的url字段構建查詢參數更加困難,因為他們必須解析來自URL的pk而不是讓pk直接可用。

For example, assuming an object on a route at /api/objects/12/ the consumer would need to parse the url field to extract the 12 in order to construct a query filtering by this object on another endpoint: /api/otherobjects/?object=12. Not a huge problem, but a bummer if you plan on doing lots of filtering.

例如,假設路徑上的對象位於/ api / objects / 12 /,則消費者需要解析url字段以提取12,以便在另一個端點上構造此對象的查詢過濾:/ api / otherobjects /?對象= 12。這不是一個大問題,但如果你計划進行大量過濾,那就太糟糕了。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/10/29/72a2edc31e216abe96c40e83f2d45f19.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com