I’ve got a model which has nearly ten fields and one of them is Boolean field.
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
nick_name = models.CharField(max_length=30)
be_anonymous = models.BooleanField(default=False)
character = models.ChoiceField(…)
…
I’ve got a ViewSet and serializers for this model and there’s an endpoint to get list of all Persons.
For some persons, be_anonymous is set to True and for those persons, I want to hide first_name and last_name from API response and instead include nick_name.
How can I hide/show those fields based on that Boolean field?
Any advice will be appreciated
My initial reaction would be that you could put that logic in your serializer. See Overriding serialization and deserialization behavior - the to_representation()
method.
Hi, Ken!
Thanks for your answer!
I think that’s a correct approach, however, I am still curious to know how I can exclude those fields.
I can check out if the boolean field is set to True or False on to_representation method.
What is the best practice to exclude fields?
Thanks
I’d entertain the idea of creating a serializer that has all three fields, first_name
, last_name
, nick_name
, then using serializers.SerializerMethodField
for them to identify whether to return the value or None
.
I like this approach because API has the same shape for all cases.
That sounds interesting but the api response will still have those keys with empty values, right?
Don’t look to make this more complicated than necessary.
The internal representation is probably going to be a Python dict (unless you’re doing something explicitly different) - so I would just check the boolean field and change the dict as desired. I wouldn’t worry about what someone considers “best practices” for this - at this layer of the code, no reasonable approach is going to be significantly different than any other.
1 Like
That is true - and there’s a lot to be said for doing it that way. It really depends upon what the client is going to expect from your response - either the field is missing or is present with a null value.
1 Like
Correct. That’s what I meant by “shape”. It depends on your clients’ expectations whether this would even be a viable approach.
1 Like
GMTA!
(with padding to make this post 20 characters.)
1 Like
It works like a charm. Very nice! 