-
-
Notifications
You must be signed in to change notification settings - Fork 43
Open
Description
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!
ivancardenasm and Janekk
Metadata
Metadata
Assignees
Labels
No labels