Skip to content

Is it possible to exclude fields by default? #303

@Alejandroid17

Description

@Alejandroid17

Is it possible to exclude fields by default? I have a serializer with a serialized field with a lot of data. This data will be used in some specific cases, but not always.

class BookSerializer(DynamicFieldsMixin, serializer.ModelSerializer):
    ....

    class Meta:
        model = Book
        fields = ['id', 'name',  '...']

class UserSerializer(DynamicFieldsMixin, serializer.ModelSerializer):
    books = BookSerializer(many=True, read_only=True)
    ....

    class Meta:
        model = User
        fields = ['id', 'username', 'email', '...', 'books']

Imagine a user with 500 books. In my logic I normally don't need to know information about those 500 books, but I do need to know information about the user (this is not a real example).

I could exclude using the query GET /user/1?query={username, -books} but it forces me to put it everywhere where it is consumed.

The idea would be something like:

class UserSerializer(DynamicFieldsMixin, serializer.ModelSerializer):
    books = BookSerializer(many=True, read_only=True)
    ....

    class Meta:
        model = User
        fields = ['id', 'username', 'email', '...', 'books']
        default_exclude = ['books']

Default:

 # `GET /user/1`

{
    "id": 100
    "username": "dummy",
    "....": "....", # without the "books" field
},

With books field:

 # `GET /user/1?query={id, username, books}`

{
    "id": 100
    "username": "dummy",
    "books": [ ..... ]
}

Thank you for everything!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions