I stumbled upon implementing a nested serializer, so I'll write it as a memo.
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_Nested in fields
            "author": UserSerializer,
            "tag": (TagSerializer, {"many": True})   #Many-to-many
        }
Response
[
    {
        "id": 1,
        "title": title_1,
        "author": 1,
        "tag": [
            1,
            2,
        ]
    },
]
Display dynamic data with parameters
| option | Explanation | 
|---|---|
| expand | Expand the specified field | 
| fields | Show only specified fields | 
| omit | The specified field is not displayed | 
expand http://localhost:8000/book/1?expand=author,tag Expand author and 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 Display only the title
[
    {
        "title": title_1,
    },
]
omit http://localhost:8000/book/1?omit=title Do not display the title
[
    {
        "id": 1,
        "author": 1,
        "tag": [
            1,
            2,
        ]
    },
]
rsinger86/drf-flex-fields - github drf-flex-fields - pypi
Recommended Posts