1

Let's say I have a class something like the following:

class PostSerializer(serializers.HyperlinkedModelSerializer):

  updated_at = serializers.DateTimeField()

  def __init__(self, *args, **kwargs):
    init = super().__init__(*args, **kwargs)
    return init 

I want to create a subclass of the PostSerializer class and I'd like to remove the updated_at constant property from the subclass-ed class.

class PostWithoutUpdatedAtSerializer(serializers.HyperlinkedModelSerializer):

  # something to remove the updated_at property ? 
  
  def somefunc(self); 
    pass 

I use a framework for example django so generally I cannot simply remove the property from the parent class, I need to subclass them. And of course obviously I need to "delete" the property, I cannot do updated_at = None, it's not a deleting.

How is it possible? Thanks.

1 Answers1

0

It's not directly possible, since the attribute doesn't exist on your derived class at all (it does on the superclass), so there's nothing to remove or reassign.

Instead, the framework you're using (Django REST Framework, my magic ball tells me), uses a metaclass that inspects the class definition for field objects and puts them into cls._declared_fields on the class (along with any fields from the superclass(es)).

The real fields for your serializer instance are acquired by get_fields(), which by default just copies _declared_fields.

In other words, if your Django REST Framework serializer subclass should not serialize that field, customize get_fields():

def get_fields(self):
    fields = super().get_fields()
    fields.pop("updated_at", None)  # remove field if it's there
    return fields
AKX
  • 152,115
  • 15
  • 115
  • 172