Serializer's fields are permanently removed if removal happens inside of a superclass #8510
Unanswered
samul-1
asked this question in
Potential Issue
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have several serializers for which I want to display certain fields only under specific conditions, such as url parameters there being in the request or the user having certain permissions.
To decouple my serializer's presentation logic from the business logic, I decided to add a
conditional_fields
attribute to the serializer'sMeta
class: it's a dict in which the keys are strings representing conditions, such as"SHOW_HIDDEN_FIELDS"
and their values are lists of field names that need to be removed if the key isn't present in the serializercontext
. Then I override my viewsets'get_serializer_context
method to get the desired values inside of context.I made a
remove_unsatisfied_condition_fields
method which does the following:The serializers making use of it look like this:
Here comes the problem: if I manually call this method inside my serializers, in their
__init__
method, like this:everything works fine.
However, if I make them inherit from a class that does it automatically, like this:
and make my serializers inherit from it, the following happens:
as soon as a request comes in that doesn't satisfy one of the serializer's
conditional_fields
condition, the field appears to be "permanently" removed from the serializer: any subsequent requests that involve it, even if they lead to having acontext
with the proper conditions to show that field, are responded to without that field. It is as if the serializer ceases to have that field forever---only redeploying my application makes it come back.In other words, if the removal happens with the method being called in a superclass, the removal is permanent and any subsequent requests involving that serializer, even from other users, will cause it to not have the removed fields. If I remove the fields inside the serializer's own init mehtod, everything works as intended.
Does this have to do with some weird Pythonic inheritance rule I'm not aware of or am I missing something about serializers?
Beta Was this translation helpful? Give feedback.
All reactions