Selecting serializer field in the DRF browsable API

For example my model and its serializer:

class Person(models.Model):
    name = models.CharField(max_length=150)
    age = models.IntegerField()
    city = models.CharField(max_length=150)


class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields = '__all__' # to select these fields on the browsable API

So my aim is to select serializer fields dynamically in order to post on the browsable API. I thought about adding a filterset class with a MultipleChoiceFilter field for serializer field names.

class PersonFilter(filters.FilterSet):
    FIELD_CHOICES = (
        (0, 'name'),
        (1, 'age'),
        (2, 'city'),
    )
    field = filters.MultipleChoiceFilter(label='fields',
                                        choices=FIELD_CHOICES)

    class Meta:
        model = Person
        fields = ['field']

What I try to do is:

Selecting the fields from the json query:

{
    "name": "Jack",
    "age": 30,
    "city": "London",
},

by using the filter on the browsable API :

obtaining the subset of fields:

{
    "name": "Jack",
    "city": "London",
}

At this point I couldn't find out how to manipulate the serializer fields variable from the filterset class. Also I don't know if it's a good practice to do it or there's a simpler way.

Back to Top