Make serializer return different fields depending on what calls it

I’m not sure if the title is actually what I want to do, or if it’s just the result of my ignorance on best practices, but here goes:

As an example, I’d like to return a list of names in JSON if someone visits root/users, but return more details if someone visits root/usersdetailed.

Would I have to make two different serializers for this, or is there some sort of logic I can throw into my serializer class to check what to change?

My serializer class looks similar to this


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['username', 'userid', 'gender']

My janky solution:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['username', 'userid', 'gender']

class UserSerializerForNamesOnly(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['username']

So part of this is going to depend upon how you set up the view(s).

Yes, there are definitely hooks you can use to dynamically configure your serializers.

See Dynamically modifying fields to get started along those lines.

Also see GitHub - dbrgn/drf-dynamic-fields: Dynamically select only a subset of fields per DRF resource, either using a whitelist or a blacklist. - less for what it actually does, which may not be what you want, but more as a real-life example of how to do what you want to do.

That was exactly what I needed! Thank you.