In my User
profile model I've included a show_email
field explicitly. So, to add this feature to my API, the UserSerializer class looks like this:
class UserSerializer(serializers.ModelSerializer):
email = serializers.SerializerMethodField('show_email')
def show_email(self, user):
return user.email if user.show_email else None
class Meta:
model = django.contrib.auth.get_user_model()
fields = ("username", "first_name", "last_name", "email")
But I don't really like it. I think it would be a lot cleaner if the field email
would be completely excluded from the serializer output it show_email
is False
, instead showing that ugly "email": null
thing.
How could I do that?
This answer comes late but for future google searches: there is an example in the documentation about Dynamically modifying fields. So, by passing an argument to the serializer, you control whether or not a field is processed:
and then in the init function in the serializer you can do something like:
Now the show_email field will be ignored by the serializer.
You could do this in your API view by overriding the method returning the response, i.e. the "verb" of the API view. For example, in a ListAPIView you would override
get()
:You would probably want to add some more checking for attributes, but that's the gist of how it could be done. Also, I would add that removing fields from some results may cause issues for the consuming application if it expects them to be present for all records.
You could override restore_fields method on serializer. Here in restore_fields method you can modify list of fields - serializer.fields - pop, push or modify any of the fields.
eg: Field workspace is read_only when action is not 'create'