2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

drf-flex-fieldsでネストしたserializerを実装する方法

Last updated at Posted at 2020-11-16

ネストしたserializerを実装するところで躓いたので、メモとして書く。
#drf-flex-fieldsをインストール

pip install drf-flex-fields

#model

model.py
class User(models.Model):
    username = models.CharField(max_length=255)


class Tag(models.Model):
    name = models.CharField(max_length=255)


class Book(models.Model):
    title = models.CharField(max_length=255)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    tag = models.ManyToManyField(Tag)

#serializer

serializers.py
from rest_flex_fields import FlexFieldsModelSerializer


class UserSerializer(FlexFieldsModelSerializer):
    class Meta:
        model = User
        fields = ("id", "username")


class TagSerializer(FlexFieldsModelSerializer):
    class Meta:
        model = User
        fields = ("id", "name")


class BookSerializer(FlexFieldsModelSerializer):
    class Meta:
        model = Book
        fields = ("id", "title", "author", "tag")
        expandable_fields = {                        #expandable_fieldsでネスト
            "author": UserSerializer,
            "tag": (TagSerializer, {"many": True})   #多対多
        }

#Response

[
    {
        "id": 1,
        "title": title_1,
        "author": 1,
        "tag": [
            1,
            2,
        ]
    },
]

#データを動的表示
パラメータを指定して動的なデータを表示する

オプション 説明
expand 指定されたフィールドを展開する
fields 指定されたフィールドのみを表示させる
omit 指定されたフィールドが表示されない
##expand
http://localhost:8000/book/1?expand=author,tag
authorとtagを展開させる
[
    {
        "id": 1,
        "title": title_1,
        "author": {
            "id": 1,
            "username": "user_1"
        },
        "tag": [
            {
                "id": 1,
                "name": "tag_1"
            },
                        {
                "id": 2,
                "name": "tag_2"
            },
        ]
    },
]

##fields
http://localhost:8000/book/1?fields=title
タイトルのみを表示させる

[
    {
        "title": title_1,
    },
]

##omit
http://localhost:8000/book/1?omit=title
タイトルを表示させない

[
    {
        "id": 1,
        "author": 1,
        "tag": [
            1,
            2,
        ]
    },
]

#参考
rsinger86/drf-flex-fields - github
drf-flex-fields - pypi

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?